我的目标是对功能getData()
的成功和错误情况进行单元测试。成功的情况下,必须调用this.success
函数。在错误情况下,必须调用this.failure
函数。
export class MyComponent implements OnInit {
constructor() {}
ngOnInit() {
this.getData();
}
getData(): void {
this.myService.getServiceData().subscribe(
//returns an observable
(result) => {
this.success(result);
},
error => {
this.failure(error);
}
);
}
}
这是我的单元测试:
describe('MyComponent', () => {
let component = MyComponent;
let fixture: ComponentFixture<MyComponent>;
let myService = jasmine.SpyObj<MyServiceClass>;
beforeEach(async(()=> {
myService = jasmine.createSpyObj('MyServiceClass', ['getServiceData']);
TestBed.configureTestingModule({
providers: [
{ provide: MyServiceClass, useValue: myService }
]
}).compileComponents();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
}));
it('should call success function', async(() => {
spyOn(component, 'success');
myService.getServiceData.and.returnValue(asyncData(myMockObj));
component.getData();
//fails. If I expect failure() to be called, it ALSO fails!
expect(component.success).toHaveBeenCalled();
}));
})
asyncData函数如下所示:
export function asyncData<T>(data: T) {
return defer(() => Promise.resolve(data));
}
为什么失败,我该如何测试这两种情况?