MockClient not intercepting the request
See original GitHub issueI know that this is under development, so I am using the last release candidate version (ie v4.0.0-rc.7).
So, I am trying to unit test my undici code, and it doesn’t work as expected or there’s something that I didn’t understand correctly. I have a very simple ts file that sends a get request. It’s presented like this:
import { request } from 'undici'
import { APIResponse } from './apiresponse.interface'
export class clientAPI {
private API_URL = 'https://example.com/tdd/everything';
public async getCall() : Promise<APIResponse> {
const { body } = await request(this.API_URL);
for await (let data of body) {
return <APIResponse> data
}
}
}
and, so after many attempts, found a good documentation about unit testing the async code, so I wrote this in my test file:
import { MockAgent, MockClient } from 'undici';
import { ClientAPI } from "./client-api"
import { APIResponse } from "./api-response.interface";
describe("client-api.ts test", () => {
it("Returns the Working parameter in a APIResponse type", async () => {
// Given
const origin = 'https://example.com'
const mockAgent = new MockAgent({ connections: 1 });
const mockClient = new MockClient(origin, {agent: mockAgent})
const clientAPI = new ClientAPI()
const expectedResponse = <APIResponse>{Working:1}
mockClient.intercept({
path: '/tdd/everything',
method: 'GET'
}).reply(200, expectedResponse)
// When
const response = await clientAPI.getCall()
// Then
expect(response).toBe(expectedResponse)
});
})
So far, the request is not intercepted and the mocking system is not working, because in my test run I can see the API response ( not what I put in the expectedResponse object ). Also, using @mcollina code was giving me an error that said Dispatcher has no method intercept, that’s why I adapted the mockClient instanciation.
Thanks for your help and GJ for the opensource contribution, you guys rock !!
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:11 (4 by maintainers)
I think casting to MockClient helps to intercept the request, but then, I got another error:
TypeError: this[kAbort] is not a function
And here’s how I casted the dispatcher to a MockClient:
const mockClient = <MockClient>mockAgent.get(origin)
Same problem here with same type of code. I have the error
TypeError: this[kAbort] is not a function