我正在尝试为简单的 Angular 2 应用程序设置单元测试。我遇到了麻烦,因为单元测试创建了多个类实例。请参阅下面的代码
app.component.ts
import { TestClass } from './test.class';
import { Service } from './service';
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<div></div>'
})
export class AppComponent {
constructor(private s: Service) {
let c = new TestClass();
}
}
测试.class.ts
export class TestClass {
static counts = 0;
constructor() {
TestClass.counts++;
if (TestClass.counts > 1)
throw "Multiple TestClass instance";
}
}
app.component.spec.ts
import { Service } from './service';
import { AppComponent } from './app.component';
import { TestBed, ComponentFixture } from '@angular/core/testing';
let fixture: ComponentFixture<AppComponent>;
describe('AppComponent', function () {
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [Service]
}).createComponent(AppComponent);
});
afterEach(() => {
fixture.destroy();
});
it('1', () => {
expect(true).toBe(true);
});
it('2', () => {
expect(true).toBe(true);
});
});
测试结果
[1] Error: Error in ./AppComponent class AppComponent_Host - inline template
:0:0 caused by: Multiple TestClass instance
有没有办法在运行下一个“it”之前删除类实例?
最佳答案
正在创建TestClass
的多个实例,因为TestBed
为每个它
创建一次AppComponent
堵塞。在上述情况下,这将是两倍。 afterEach
在每个 it
block 之后运行一次,您可以在其中重置静态变量 counts
describe('AppComponent', function () {
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [Service]
}).createComponent(AppComponent);
});
afterEach(() => {
fixture.destroy();
TestClass.counts = 0
});
......
这样您就不必删除 TestClass
本身来重置 counts
变量
编辑:替代方法:
由于您已经在 afterEach
block 中销毁组件,因此可以在 AppComponent
上使用 ngOnDestroy
生命周期 Hook 来重置 count 变量就在那里。这里的逻辑是,如果组件本身被销毁,那么TestClass
的实例也会被销毁。必须以这种方式完成,因为 typescript 没有析构函数的概念
@Component({
selector: 'my-app',
template: '<div></div>'
})
export class AppComponent implements OnDestroy{
constructor(private s: Service) {
let c = new TestClass();
}
ngOnDestroy() {
TestClass.counts = 0;
}
}
关于unit-testing - Angular 2 单元测试 - 多个类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40722994/