我发现在 Angular 中进行测试非常困难。为了处理尽可能少的样板文件,我尝试进行 jest/spectator 单元测试。
我想测试一个解析器。它应该从 catchError() 返回一个 Contact[] 或 EMPTY 类型的 Observable。结果只有两种。
以下是我到目前为止所拥有的,我知道它很粗糙。
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> |
Observable<never> {
return this.contactsService.getContacts()
.pipe(
catchError(err => EMPTY),
tap(res => res)
);
}
describe('ContactsResolverService', () => {
let spectator: SpectatorService<ContactsResolverService>;
const createService = createServiceFactory({
service: ContactsResolverService,
imports: [HttpClientModule]
});
beforeEach(() => {
spectator = createService();
});
it('should call the resolve class method', fakeAsync ( () => {
const contactsService = spectator.inject(ContactsService);
contactsService.getContacts.andReturn( of( ['ContactObj', 'ContactObj', 'ContactObj']) );
const mockSnapshot = createSpyObj<RouterStateSnapshot>('RouterStateSnapshot',
['toString']);
const mockR = createSpyObj<ActivatedRouteSnapshot>('ActivatedRouteSnapshot',
['toString']);
flushMicrotasks();
const r = spectator.service.resolve(mockR, mockSnapshot)
expect(r).toHaveBeenCalled();
}));
});