在您的规范文件中。
添加
export class FakeSubject {
next(value: any) {}
asObservable() {}
}
配置您的测试平台:
TestBed.configureTestingModule({
providers: [{ provide: Subject, useClass: FakeSubject }],
}),
在每次测试之前添加一个服务获取器。
beforeEach(() => {
service = TestBed.get(AlertService);
});
添加测试,您可以将此示例用于另一个测试。
it('success alert ', () => {
const spy = spyOn(service, 'alert');
const message = 'hi!';
service.success(message);
expect(spy).toHaveBeenCalledWith(new Alert(message, AlertType.Success));
});
和你的实用方法:
it('alert ', () => {
subject = service['subject'];
const spy = spyOn(subject, 'next');
const alert = new Alert('hi', AlertType.Success);
service.alert(alert);
expect(spy).toHaveBeenCalledWith(alert);
});
it('clear ', () => {
subject = service['subject'];
const spy = spyOn(subject, 'next');
service.clear();
expect(spy).toHaveBeenCalledWith(null);
});