【问题标题】:Angular 9 + jest : unit test, mock a promise and check method called thenAngular 9 + jest:单元测试,模拟一个promise,然后调用check方法
【发布时间】:2020-06-27 20:05:45
【问题描述】:

我需要帮助,我不知道如何模拟 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);
}

我正在尝试测试此函数,并且我想模拟(或存根?我不知道区别)当 promise 解决时的 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
  });

}

有人可以帮助我吗? 真诚的

【问题讨论】:

    标签: javascript angular unit-testing jestjs


    【解决方案1】:

    有两个选项可供选择:
    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 调用时不会引发错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-30
      • 2018-04-02
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2014-04-16
      相关资源
      最近更新 更多