【问题标题】:The "Angular" way of testing a component测试组件的“Angular”方式
【发布时间】:2016-08-08 09:10:38
【问题描述】:

在 Angular 1 中,如果我写了一个组件,我会确保:

  • 依赖项,例如服务被模拟。
  • 为组件中的方法编写单元测试。
  • 组件正在调用服务来检索数据 expect(service.method).toHaveBeenCalled()
  • 组件正在更新给定更新模型的视图。

我一直在对Angular 2组件测试进行一些研究,对于我能找到的所有文章,似乎都在进行如下测试;

  • 创建一个返回固定结果的服务模拟(例如:'Test Quote')
  • 期望视图包含来自模拟服务的结果(例如,某处有一个具有<div>Test Quote</div> 的 div)。

以下是此类文章的一些示例(基本上是 google 上“Angular 2 组件测试”的顶级结果)

由于 NG2 在其测试框架@angular/core/testing 中没有提供任何间谍,建议完全避免使用粗体的步骤?还是我们应该包括茉莉花来接触间谍?

【问题讨论】:

    标签: javascript unit-testing testing angular


    【解决方案1】:

    如果您特别希望测试组件渲染,那么您可以使用TestComponentBuilder,如您问题中提到的博客中所述。

        describe('MyComponent', () => {
    
          it('should render list', async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
            return tcb.createAsync(MyComponent).then((componentFixture: ComponentFixture) => {
              const element = componentFixture.nativeElement;
             //... get the element you want to check 
              componentFixture.detectChanges();
              expect(element).toHaveText('test div');
              expect(element.querySelectorAll('div').length).toBe(1);
            });
          }));    
    }));
    

    如果在组件中调用了一个服务,那么你想在beforeEachProviders()beforeEach() 方法中使用inject,例如:

    beforeEach(() => {
        addProviders([
          provide(LoginService, { useClass: MockLoginService }),
          UserService
        ]);
      });
    

    当您想在组件中模拟服务调用时,使用jasmine 间谍以及and.callThroughand.returnValue 等方法非常有用。此外,请查看 Angular 团队成员 julie raplh 的 this repo。

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2018-07-22
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多