最近在给组件补充测试,顺便整理一下常用的测试方法 spyOn、spyOnProperty、createSpy、createSpyObj等的关键知识点。
spyOn
- Jasmine 具有称为 spies 的双重测试功能。 spy可以存任何函数并跟踪对它的调用和所有参数。 spy仅存在于定义它的 describe 或 it 块中,并且在每个spec之后删除。
spyOn(obj: Object, methodName: string) → {Spy}
参数1:要安装spy的对象。参数2:要替换为 Spy 的方法的名称。返回值是一个Spy。- 以下示例包含toHaveBeenCalled、toHaveBeenCalledTimes、toHaveBeenCalledWith的使用。
// The example comes from Jasmine official
describe("A spy", function() {
var foo, bar = null;
beforeEach(function() {
foo = {
setBar: function(value) {
bar = value;
}
};
spyOn(foo, 'setBar'); // const fooSpy = spyOn(foo, 'setBar');
foo.setBar(123);
foo.setBar(456, 'another param');
});
it("tracks that the spy was called", function() {
expect(foo.setBar).toHaveBeenCalled(); // expect(fooSpy).toHaveBeenCalled();
});
it("tracks that the spy was called x times", function() {
expect(foo.setBar).toHaveBeenCalledTimes(2);
});
it("tracks all the arguments of its calls", function() {
expect(foo.setBar).toHaveBeenCalledWith(123);
expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
});
it("stops all execution on a function", function() {
expect(bar).toBeNull();
});
it("tracks if it was called at all", function() {
foo.setBar();
expect(foo.setBar.calls.any()).toEqual(true);
});
});
实际应用:
@Component({
template: `
<my-date-picker [ngModel]="value" (ngModelChange)="thyOnChange($event)"></my-date-picker>
`
})
class MyTestComponent {
value: Date | number;
thyOnChange(): void {
}
}
describe('test date picker component event via spy on', () => {
let fixture: ComponentFixture<MyTestComponent>;
let fixtureInstance: MyTestComponent;
let debugElement: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, MyDatePickerModule],
declarations: [MyTestComponent]<