[英]How do I properly test using a mocked service that returns a Promise?
[英]How do I Unit Test an Async method that returns a Promise
我正在尝试使用在我的 Angular 应用程序中返回承诺的方法来测试服务。
但我不断收到错误Async 功能未在 5000 毫秒内完成
我的服务看起来像这样
public async startApp(data) {
if (data === { }) this.logout()
const url = environment.API_HOST + environment.ENDPOINT + '/start-app'
return this.sendRequest<responseType>(url, data).toPromise()
}
private sendRequest<T>(url: string, data: any): Observable<T> {
return this.http.post<T>(
url, data, { headers: this.headers(), observe: 'response', responseType: 'json' }
).pipe(
map((resp: any) => {
return resp.body
}))
}
我的规范文件如下所示:
describe('MyService', () => {
let service: MyService
TestBed.configureTestingModule({ providers: [ MyService ] })
service = TestBed.get(MyService)
})
it('should start app', async (done: DoneFn) => {
const res = await service.startApp({ data: 'someData' })
done()
})
我究竟做错了什么?
如果可能的话,我会避免监视sendRequest
因为它是一个私有方法,否则我无法对其进行测试
看到您的应用程序正在执行 http,您需要将其注入到您的配置中。
import { HttpClientTestingModule,
HttpTestingController } from '@angular/common/http/testing';
......
describe('MyService', () => {
let httpTestingController: HttpTestingController;
let service: MyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [MyService],
imports: [HttpClientTestingModule],
});
// get a handle on the HTTPController
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(CoursesService);
});
afterEach(() => {
// verify no pending requests after each test
httpTestingController.verify();
});
it('should start app and send a post request', async (done: DoneFn) => {
service.startApp({ data: 'someData' }).then(response => {
expect(response.body).toBe('helloWorld');
// put the rest of your assertions here.
done();
});
const mockResponse = { body: 'helloWorld' }; // mock the response to what you would like
const req = httpTestingController.expectOne(... put here whatever the url, data is/ will resolve to);
expect(req.request.method).toEqual('POST');
// for the next HTTP request for that URL, give this as the response
req.flush(mockResponse);
});
});
startApp
调用一个函数,该函数以可观察的方式进行 API 调用,但您将其转换为承诺,但我很确定我为您提供的内容应该很好。
适合您的链接: https : //medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.