javascript - 在 Jasmine 测试期间,Angular 4 fixture 组件持续存在于 DOM 中

标签 javascript unit-testing angular typescript jasmine

在真实浏览器中运行 Jasmine 时,我注意到 TestBed fixture 组件没有在 DOM 中被销毁,并且在测试结束后仍然存在:

enter image description here

这是一个经过测试的组件:

@Component({
  selector: 'test-app',
  template: `<div>Test</div>`,
})
class Test {}

还有一个测试(plunk)。

  let component;
  let fixture;
  let element;

  beforeAll(() => {
    TestBed.resetTestEnvironment();

    TestBed.initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting()
    );
  });

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [Test],
    })
    .compileComponents();

    fixture = TestBed.createComponent(Test);
    component = fixture.componentInstance;
    element = fixture.debugElement.query(By.css('div')).nativeElement;

    fixture.detectChanges();
  });

  afterEach(() => {
    fixture.destroy();
  });

  it('should compile Test', () => {
    expect(element).toBeTruthy();
  });

为什么 Test 组件实例没有从 DOM 中删除,应该如何解决?

为什么要将 fixture 组件添加到 DOM 中?它们可以像 AngularJS 中的 $rootElement 那样从 DOM 中分离出来吗?

最佳答案

Jasmine 和 Angular 都不会自动删除它,也许是为了帮助您获得有关测试执行的更多详细信息。

要删除它,您只需使用 afterEach(...) ,比如:

beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  comp = fixture.componentInstance;
  debugElement = fixture.debugElement;
  element = debugElement.nativeElement;
});

afterEach(() => {
  document.body.removeChild(element);
});

对于非 Angular 用户:

afterEach(() => {
    document.body.innerHTML = '';
});

Above clears all default <script> tags, but that does not matter (because they did already run, and Karma does never refresh the browser, at least not till all tests finish).

关于javascript - 在 Jasmine 测试期间,Angular 4 fixture 组件持续存在于 DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43645662/

相关文章:

javascript - 无法使用 Node-Cron 在 module.exports 对象中执行回调?

angular - TransferHttpCacheModule 与 transferstate api 之间的区别

javascript - Angular(2 +) 检测 Angular 形式(响应式(Reactive))中的数据是否已更改

javascript - (amCharts)我有一个图表,其中数据有两个不同的前缀。有什么方法可以告诉函数哪些数据具有哪个前缀?

javascript - 如何从 Bing api 获取头条新闻

javascript - 有没有办法在 CoffeeScript 中包含文件?

java - 模拟使用外部类的方法,mockito

unit-testing - Angular 2 : How to mock ChangeDetectorRef while unit testing

javascript - 运行并添加单元测试到nodejs项目

html - Angular 组件如何使用用户定义的样式表?