【发布时间】:2020-02-06 02:17:09
【问题描述】:
我有 Angular HTTP 服务,可以进行一些 HTTP 调用。 这是我的服务示例:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class APIService {
constructor(private readonly http: HttpClient) {}
public async getUsers<T>(): Promise<T[]> {
return await this.http.get<T[]>('/api/users').toPromise();
}
}
这是我的spec.ts 文件APIService:
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { APIService } from './api.service';
describe('API Service', () => {
let service: APIService;
let controller: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [APIService]
});
service = TetsBed.get(APIService);
controller = TestBed.get(HttpTestingController);
});
it('should create the API service', () => {
expect(service).toBeTruthy();
});
it('should get users', () => {
const expected = [{id: 1, email: 'email1@domain.tld'},
{id: 2, email: 'email2@domain.tld'}];
service.getUsers<MyUserClass>().then((res) => {
expect(res).toEqual(expected);
controller.verify();
});
controller.expectOne('/api/users').flush(expected);
});
});
似乎一切正常,因为当我运行 ng test 时,我收到这样的消息:
ERROR: 'Spec 'API Service should get users' has no expectations.'
HeadlessChrome 77.0.3865 (Windows 10.0.0): Executed 13 of 15 SUCCESS (0 secs / 0.256 secs)
HeadlessChrome 77.0.3865 (Windows 10.0.0): Executed 15 of 15 SUCCESS (0.42 secs / 0.28 secs)
TOTAL: 15 SUCCESS
TOTAL: 15 SUCCESS
TOTAL: 15 SUCCESS
当我在下一个代码下更改某些内容时,我得到了错误。
.then((res) => {
// expect(res).toEqual(expected);
expect(res).toBeNull();
controller.verify();
});
所以上面的代码很好并且可以工作。
那么,为什么我会收到一条错误消息:ERROR: 'Spec 'API Service should get users' has no期望。'?有什么想法吗?
我猜,async/await 可能会导致这个问题,因为我实际上并没有等待它,但是它执行时没有错误,当我输入错误的数据时,它就会失败。
我还尝试将所有内容包装到 async/fakeAsync 方法中 - 不走运。
【问题讨论】:
标签: angular typescript unit-testing jasmine karma-jasmine