Ng5 Karma Jasmine 测试渲染组件而不是结果页面

2023-12-28

假设我有一个非常简单的“创建”单元测试,这样ng cli为您生成:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [
        HttpClientTestingModule,
        FormsModule,
        RouterTestingModule.withRoutes([{ path: 'home', redirectTo: '/' }])
      ],
      providers: [SomeService1, SomeService2, { provide: SomeService3, useValue: {} }],
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

现在当我像这样运行这个测试时ng test --browser=Chrome我不是查看 Karma 结果页面,而是查看我的组件。

我的 CLI 版本是1.6.3, Karma 1.7.1, 角5.2.0,操作系统 macOS。

Update我的浏览器被捕获,karma 加载,测试运行,但我看到的不是 karma 结果,而是全屏组件,因为它的 css 覆盖了它们的结果。如果我找到 div 并在 DOM 中删除它,我可以看到 Karma 结果。

我只是期待 Angular 删除该节点。


我不太确定为什么组件的 DOM 编译在测试结束后仍然保留,但我注意到它只发生在最后运行的测试中。如果您可以添加另一个也编译组件但不添加全屏组件的组件测试,则前一个组件会被正确删除。因此,简单地添加更多测试可能是最简单的解决方案。

但如果这还不够,这里有两种可能的解决方案:

1. 不要编译它

如果您的测试不涉及验证生成的 DOM,您可以直接使用该组件来简化测试的安排。

describe('MyComponent', () => {
  TestBed.configureTestingModule({
    // declarations: [MyComponent],
    imports: [
      HttpClientTestingModule,
      FormsModule,
      RouterTestingModule.withRoutes([{ path: 'home', redirectTo: '/' }]),
    ],
    // 1. Add the component as a provider.
    providers: [MyComponent, SomeService1, SomeService2, { provide: SomeService3, useValue: {} }],
    schemas: [NO_ERRORS_SCHEMA],
  });

  it('should do thing #1', () => {
    // 2. Test it like you would test a service.
    const comp = TestBed.get(MyComponent);
    expect(comp.value).toBe(false, 'off at first');
    comp.doThing1();
    expect(comp.value).toBe(true, 'on after click');
    comp.doThing1();
    expect(comp.value).toBe(false, 'off after second click');
  });

  it('should do thing #2', () => {
    const comp = TestBed.get(MyComponent);
    expect(comp.value2).toMatch(/is off/i, 'off at first');
    comp.doThing2();
    expect(comp.value2).toMatch(/is on/i, 'on after clicked');
  });
});

更多信息here https://angular.io/guide/testing#component-class-testing.

2.从DOM中删除它

如果您确实需要测试 DOM,我发现的唯一解决方法是在完成测试后显式删除 HTML 元素。

  afterEach(() => {
    if (fixture.nativeElement && 'remove' in fixture.nativeElement) {
      (fixture.nativeElement as HTMLElement).remove();
    }
  });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ng5 Karma Jasmine 测试渲染组件而不是结果页面 的相关文章