[英]Unit Test HttpClient - Angular/Karma
我正在閱讀一些有關單元測試的文章,並找到了一些非常有用的示例。 我遇到的大多數示例似乎都是對功能進行單元測試的功能,該功能使用Angular HttpClient
做一些事情,並且大多數情況如下所示:
it('should return an Observable<User[]>', () => {
const dummyUsers = [
{ login: 'John' },
{ login: 'Doe' }
];
service.getUsers().subscribe(users => {
expect(users.length).toBe(2);
expect(users).toEqual(dummyUsers);
});
const req = httpMock.expectOne(`${service.API_URL}/users`);
expect(req.request.method).toBe("GET");
req.flush(dummyUsers);
});
https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712
這意味着.getUsers()
返回一個可觀察值。 但是,在我的應用程序中,我沒有返回可觀察到的結果。 我的幾乎所有HttpClient
調用都與此類似:
async getCurrentUser(): Promise<UserInfo> {
return await this._httpClient.get(`/api/me`).toPromise();
}
如何在Karma中對調用HttpPost或HttpGet的函數進行單元測試?
嘗試:
it('should get current user', async () => {
const result = service.getCurrentUser();
console.log('RESULT', result);
const req = httpMock.expectOne(`/api/me`);
const test = req.flush({test: 'ing'});
console.log('REQUEST', test);
expect('a').toEqual('a');
});
我想我想得太多了,但是我設法通過使用.then使其正常工作.then
而不是像在正常(非測試)調用中那樣使用await
:
it('should get current user', async () => {
const response = new CustomResponseClass();
response.success = true;
response.error = null;
const user = new User();
user.userId = 1;
user.name = 'Test User';
response.data = user;
service.getCurrentUser().then( _user => {
console.log('USER', _user);
// TODO: Some more unit tests here...
});
const req = httpMock.expectOne('/api/me');
expect(req.request.method).toEqual('GET');
req.flush(response);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.