簡體   English   中英

Angular 9 + jest:單元測試,模擬一個承諾並檢查然后調用的方法

[英]Angular 9 + jest : unit test, mock a promise and check method called then

我需要幫助,我不知道如何模擬 Promise 並檢查 then() 部分中調用的方法。

當我單擊表單的保存按鈕時,我的代碼如下所示:

// File : myComponent.ts
save() {
   const myObject = new MyObject({field: this.form.value.field});

   this.myService.saveObject(myObject).then(() => { // I'd like to mock this
     this.closeDialog(true);
  }, error => {
     this.otherFunction(error);
  });
}


// File : myService.ts
saveOject(myObject: MyObject): Promise<any> {
  return this.myApi.save(myOject).toPromise().then(res => res);
}


// File : myApi.ts
save(myObject: MyObject) {
  return this.http.post('url, myObject);
}

我正在嘗試測試這個函數,我想模擬(或存根?我不知道有什么區別)saveObject 函數,當承諾得到解決時,情況並非如此。

我的實際測試文件如下所示:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let myService: MyService;

  beforeEach(async (() => {
     TestBed.configureTestingModule(
   ).compileComponents();

   myService = TestBed.inject(MyService);
  }

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    spyOn(myService, 'saveOject').and.returnValue(new Promise(resolve => resolve()));
  });

  it('should call closeDialog method when save form is successful', () => {
     const spyCloseDialog = jest.spyOn(component, 'closeDialog');

     component.save();
     fixture.detectChanges(); // It's a test, I don't know if it's useful
     expect(spyCloseDialog).toHaveBeenCalledTimes(1); // It's 0 because I don't know how to be in the then part of my function
  });

}

有人可以幫助我嗎? 真摯地

有兩個選項可供選擇:
1)使用fakeAsync ,例如:

it('should call closeDialog method when save form is successful', fakeAsync(() => {
     const spyCloseDialog = jest.spyOn(component, 'closeDialog');

     component.save();
     tick(50);
     expect(spyCloseDialog).toHaveBeenCalledTimes(1);
}));

2)把你的expect放在里面then ,例如

component.save().then(() => expect(spyCloseDialog).toHaveBeenCalledTimes(1)); 

在您的測試中,您應該導入HttpClientTestingModule ,以便測試成功運行並且在 angular 嘗試啟動 http 調用時不會引發錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM