【问题标题】:Use jest-mock-extended and Spectator for angular components testing使用 jest-mock-extended 和 Spectator 进行角度组件测试
【发布时间】:2021-02-24 23:25:37
【问题描述】:

我已经成功地使用jest-mock-extended 来测试服务,它对我来说很好用。它简单、易于使用且输入安全。

现在我必须测试 Angular 组件。为此,我找到了Spectator。我设法使用SpectatorHost 功能为没有服务的简单组件编写测试。现在我必须使用我应该模拟的服务来测试一个组件,但我真的很难做到。

出于这个原因,我想知道是否有办法将使用jest-mock-extended 创建的模拟注入使用SpectatorHost 在内部生成的组件中。

通过这种方式,我还将使用相同的库来模拟我项目中的服务。

【问题讨论】:

    标签: angular unit-testing jestjs angular-spectator spectator


    【解决方案1】:

    我找到了如何整合这两个库:

       describe('MyComponent', () => {
          // SpectatorHost object and factory
          let host: SpectatorHost<MyComponent>;
          const createHost = createHostFactory({
             component: MyComponent,
             mocks: [MyService], // Automatically mock service used by the component
          });
    
          // MockProxy object from jest-mock-extended
          let myServiceMock: MockProxy<MyService>;
    
          // Init and reset service before each test
          beforeEach(() => {
             myServiceMock = mock<MyService>();
             
             mockReset(MyService);
          });
    
          it('...', () => {
             // Mock whatever function in the service
             myServiceMock.doSomething.mockReturnValue('Mock');
             host = createHost('<my-component></my-component>', {
                providers: [{ provide: MyService, useValue: myServiceMock }] // Pass mocked service to the component
             });
    
             // Rest of the test...         
        });
    

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 2023-02-17
      • 2020-12-18
      • 2021-02-20
      • 2019-01-27
      • 2021-02-03
      • 2019-02-24
      • 2020-05-25
      相关资源
      最近更新 更多