繁体   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