[英]How test request http with parameters with jest - angular
我正在用 Jest 測試角度服務。
我可以模擬我的 httpClient,但我有一個問題是我無法使用參數測試 url(例如:“ http://localhost:8080/api/feature/num?id=25663 ”)。
這是我的測試代碼:
describe('MyService', () => {
let myService: MyService;
const httpMock = {get: jest.fn(() => of(dataMock))};
const provide = (mock: any): any => mock;
beforeEach(() => {
myService= new MyService(provide(httpMock));
});
test('should created', () => {
expect(myService).toBeTruthy();
});
test('should retrieve one user', (done) => {
const number = 26586;
const url = 'http://localhost:8080/api/feature/num?number=25663';
myService.getNumero(number).subscribe(
res => {
expect(httpMock.get).toBeCalledWith(url);
expect(res.number).toBe(number);
expect(res.city).toEqual('PARIS');
done();
});
});
});
在我的控制台中我有這個錯誤:
Error: Uncaught [Error: expect(jest.fn()).toBeCalledWith(...expected)
Expected: "http://localhost:8080/api/feature/num?number=25663"
Received: "http://localhost:8080/api/feature/num, {
"params": {
"cloneFrom": {
"cloneFrom": null,
"encoder": {},
"map": null,
"updates": null
},
"encoder": {},
"map": null,
"updates": [{"op": "a", "param": "number", "value": "25663"}]
}
}
通常我喜歡這樣
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
...
describe('MyService', () => {
let injector: TestBed;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [],
});
injector = getTestBed();
httpMock = injector.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
...
it('should return number and city', () => {
const expectedResult: {
number: 26586,
city: 'PARIS'
};
const service : MyService = TestBed.get(MyService);
service.getNumero(number)
.pipe(
first(),
)
.subscribe((data) => {
expect(data).toMatchObject(expectedResult);
});
const req = httpMock.expectOne(`http://localhost:8080/api/feature/num?number=25663`);
expect(req.request.method).toBe('GET');
req.flush(expectedResult);
});
您可以使用 jest 的解析運算符:
it('should return number and city', () => {
const expectedResult: {
number: 26586,
city: 'PARIS'
};
const service : MyService = TestBed.get(MyService);
expect(service.getNumero(number).toPromise())
.resolves.toMatchObject(expectedResult);
const req = httpMock.expectOne(`http://localhost:8080/api/feature/num?number=25663`);
expect(req.request.method).toBe('GET');
req.flush(expectedResult);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.