内容:测试返回依赖于嵌套 http 调用的 Promise 的异步函数
有:Angular 9,茉莉花 3.4.0
问题:错误:超时 - 异步回调未在 5000 毫秒内调用(由 jasmine.DEFAULT_TIMEOUT_INTERVAL 设置)错误:预期没有打开请求,发现 1:GET http://localhost:9876/24a27be6-9f62-4156-8fd4-adcd945ec909
import ...
export interface UserData {...}
@Injectable()
export class UserDataManagementService {
private userID: string | undefined;
public userData: UserData;
constructor(...) {}
private async loadUserData() {
const headers = await this.getHeaders();
return this.httpClient
.get<UserData>(window.location.origin + '/' + this.userID, { headers })
.toPromise()
.then((data) => {
this.userData = data;
})
.catch((e) => {
this.logger.error('Error in loadUserData: ', e);
});
}
private async getHeaders() {...}
}
这是我的测试:
import ...
const mockUserData: UserData = {...};
describe('UserDataManagementService', () => {
let httpTestingController: HttpTestingController;
let service: UserDataManagementService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
UserDataManagementService,
...
],
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(UserDataManagementService);
});
afterEach(() => {
httpTestingController.verify();
});
describe('loadUserData', () => {
it('should return user data on success', (done) => {
(service as any).userID = '24a27be6-9f62-4156-8fd4-adcd945ec909';
(service as any).loadUserData().then(() => {
expect((service as any).userData).toEqual(mockUserData);
const req = httpTestingController.expectOne(
'http://localhost:9876/24a27be6-9f62-4156-8fd4-adcd945ec909',
);
expect(req.request.method).toEqual('GET');
req.flush(mockUserData);
done();
});
});
});
});
到目前为止我尝试了什么:
- 试图将默认超时时间增加到 20000 毫秒 -没有用
- done / async / await 等的不同组合。
- 在 then() 之外放置 httpTestingController.expectOne (实际上没有意义,但我已经尝试了一切)
- 如果我将 httpTestingController.verify() 放入此测试,则错误“预期没有打开的请求...”消失
这不是以下内容的重复: