Ng5 Karma Jasmine test renders component instead of result page

zai*_*man 6 karma-jasmine angular

Let's say i have a very simple 'create' unit test, kind that ng cli generates for you:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

Now when i run this test like so ng test --browser=Chrome instead of looking at Karma results page, i am looking at my component.

My CLI version is 1.6.3, Karma 1.7.1, Angular 5.2.0, OS macOS.

Update My browser is captured, karma loads, tests run but instead of karma results i see my full-screen component because it's css overlays their results. If i find the div and delete it in the DOM, i can see Karma results.

I was just expecting Angular to remove that node.

Rul*_*luk 6

我不太确定为什么在测试结束后仍保留该组件的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');
  });
});
Run Code Online (Sandbox Code Playgroud)

更多信息在这里

2.将其从DOM中删除

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

  afterEach(() => {
    if (fixture.nativeElement && 'remove' in fixture.nativeElement) {
      (fixture.nativeElement as HTMLElement).remove();
    }
  });
Run Code Online (Sandbox Code Playgroud)