Jest 模拟一个构造函数

时间:2021-05-04 20:47:49

标签: angular unit-testing jestjs

我正在使用 Angular 和 Jest 来模拟一个类。我发现在模拟构造函数时遇到困难,因为在构造函数中调用了测试函数。关于如何用玩笑模拟构造函数的任何输入都会有所帮助

export class AppComponent {


constructor(){

this.test();

}

test(){

return 'Test'
}
}

测试

describe( 'AppComponent', () => {
    let fixture: WorkerFormComponent;

    beforeEach( () => {
        
        fixture = new AppComponent(
            
        );
    });

1 个答案:

答案 0 :(得分:0)

为什么不尝试只模拟构造函数内部的方法,而不是整个构造函数本身?

describe('AppComponent', () => {
  let component: WorkerFormComponent;
  let fixture: ComponentFixture<WorkerFormComponent>;

  beforeEach(() => {
    fixture = TestBed.createComponent(WorkerFormComponent);
    component = fixture.componentInstance;
  });

  it('should mock and call the test function', () => {
    const testFnSpy = jest.spyOn(component, 'test')
                          .mockImplementation(() => 'Mock Value Returned');
    component.fireMethod(); // some method unrelated to the constructor
    expect(testFnSpy).toHaveBeenCalled();
  });
});

此解决方案使用间谍,如果您想删除 mockImplementation,您可以这样做。

相关问题