angular - 比较异步函数内部的数据时,Angular HttpClient 单元测试不会失败
问题描述
我正在尝试对一些简单的 GET 请求进行单元测试,无论我做什么,我都不能让测试失败。
如果我将其更改('GET')
为('POST')
它将失败,但无论如何所有的 api 数据都会通过。
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { mockPhoneNumbers } from '../mocks/data/phoneNumbers.mock';
import { PhoneNumberApiService } from './phone-number-api.service';
describe('PhoneNumberApiService', () => {
let service: PhoneNumberApiService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [PhoneNumberApiService],
});
service = TestBed.get(PhoneNumberApiService);
httpTestingController = TestBed.get(HttpTestingController);
});
afterEach(() => {
// After every test, assert that there are no more pending requests.
httpTestingController.verify();
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should get the phone numbers successfully', () => {
service
.getPhoneNumbers()
.subscribe(phoneNumbers => {
expect(phoneNumbers).toEqual('bob');
expect(phoneNumbers[0].id).toEqual('b8bfea4d-a26f-9e4e-cbd4-39eb69cdaa58');
expect(phoneNumbers[1].friendlyName).toEqual('Dev Test');
});
const req = httpTestingController.expectOne('phoneNumbers');
expect(req.request.method).toEqual('GET');
req.flush(mockPhoneNumbers);
});
it('should get the phone number details successfully', () => {
const { id: phoneNumberId } = mockPhoneNumbers[0];
service
.getPhoneNumberDetails(phoneNumberId)
.subscribe(phoneNumber => expect(phoneNumber).toEqual(mockPhoneNumbers[0]));
const req = httpTestingController.expectOne(`phoneNumbers/${phoneNumberId}`);
expect(req.request.method).toEqual('GET');
req.flush('bob');
});
});
当然用模拟数据刷新请求然后期望模拟数据bob
是错误的。在底部测试中,刷新请求bob
并期望数据等于数组中的第一个电话号码应该会失败。
解决方案
关于你的测试的问题是你让你的“它”功能和期望异步没有明确告诉茉莉。
您需要在 other 中使用 done 函数来告诉测试等待某些东西(在这里查看关于 jasmine 异步测试的好教程)
遵循基于您的代码的示例:
...
//Receive the done function like this
it('should get the phone numbers successfully', (done) => {
service
.getPhoneNumbers()
.subscribe(phoneNumbers => {
expect(phoneNumbers).toEqual('bob');
expect(phoneNumbers[0].id).toEqual('b8bfea4d-a26f-9e4e-cbd4-39eb69cdaa58');
expect(phoneNumbers[1].friendlyName).toEqual('Dev Test');
//Tell the test that only in here all the work was done
done();
});
const req = httpTestingController.expectOne('phoneNumbers');
expect(req.request.method).toEqual('GET');
req.flush(mockPhoneNumbers);
});
....
此外,为了回答您的猜测,jest 是一个测试运行程序,并且构建在 jasmine 框架之上(这意味着 jest 语法类似于 jasmin,但不相等)。但是对于这种情况,我想使用 done 将解决您的问题。
推荐阅读
- php - 库的扩展名和二进制文件是什么意思?
- flutter - 当用户在 Flutter 中离开当前屏幕时调用函数
- ios - 相机沿x轴移动时如何限制SCNNode移动?
- javascript - 如何使用 JINJAVA 将 Java 字符串值或字符串列表传递给 javascript
- php - 来自 PHP CLI 的 gRPC 调用被卡住
- python - 如果值不存在则如何创建条件然后发生一些顺序动作,如果值不存在则发生其他动作
- google-sheets - 使用谷歌表格在图表中保持单元格引用不变?
- jquery - 使用 php 使用 ajax 上传 jquery 文件
- mysql - 两个表之间的查询慢
- javascript - 滚动 - 内容拉伸动画