Tatiana
09/27/2022, 12:56 PMThe following request was expected but not received:
Method: GET
Path: /events/1cb9eb9e
We are using React Testing Library and jest for testing. I am using PactV3 for contract testing.
My code:
const provider = new PactV3({
dir: path.resolve(process.cwd(), 'pacts'),
consumer: 'MyConsumer',
provider: 'MyProvider'
});
const EXPECTED_BODY = {
"name": "test event",
"id": "1cb9eb9e",
"teamId": "dummy_tid",
};
function flush() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
function createWrapper({ children }: { children: React.ReactElement }) {
return <Provider store={makeStore()}>{children}</Provider>;
}
describe('GET /event/{id}', () => {
it('returns an event', async () => {
provider
.given('I can get an event')
.uponReceiving('a request for one event with the builder pattern')
.withRequest({
method: 'GET',
path: '/events/1cb9eb9e'
})
.willRespondWith({
status: 200,
body: EXPECTED_BODY,
});
return provider.executeTest(async () => {
//Arrange - we are using env var to provide a base url
process.env.API_HOST = '<http://localhost:8082>';
console.log(process.env.API_HOST);
//Act
const { result } = renderHook( () => useGetEventQuery({ id: '1cb9eb9e' }),{
wrapper: createWrapper,
});
await flush();
console.log(result.current);
// Assert: check the result
expect(result.current.data?.id).toBe("1cb9eb9e");
});
});
});
I receive an undefined data, the console.log(result.current); returns:
{
status: 'pending',
endpointName: 'getEvent',
requestId: '6OJC915gB1DnUNUKk7zPP',
originalArgs: { id: '1cb9eb9e' },
startedTimeStamp: 1664282999059,
isUninitialized: false,
isLoading: true,
isSuccess: false,
isError: false,
data: undefined,
currentData: undefined,
isFetching: true,
refetch: [Function: refetch]
}
Shouldn’t the data be set by Pact mock server?
Please help me to understand what I am doing wrong and why my request is not being received by the mock server🙏Tatiana
09/27/2022, 1:16 PMOk. I can't help you other than tell you that the error message means that your request is not being received by the mock server. Either you're not sending it, or it's not going to the right place, or you are sending it, but it is not what you set up in the test, or your test isn't waiting for the request to be sent before asking pact if it was sent.
1. I can say that I send my request, it’s here:
const { result } = renderHook( () => useGetEventQuery({ id: '1cb9eb9e' }),{
wrapper: createWrapper,
});
2. also, I am waiting for the request is done, I use await flush() function after the request
3. As I can see, I send and try to get a correct data, I checked the response schema and I have all these provided fields.
4. I can’t get this it's not going to the right place , how I can check it?Yousaf Nabi (pactflow.io)
mockserver.url
https://github.com/pact-foundation/pact-js/blob/master/docs/consumer.md
I assume your code is making requests to
<http://localhost:8082>
looking at your code, in setting the env var, but the pact mock provider will be listening on a different portYousaf Nabi (pactflow.io)
Tatiana
09/27/2022, 1:55 PMmockserver.url now, such as
return provider.executeTest(async (mockserver) => {
//Arrange
process.env.API_HOST = mockserver.url;
console.log(process.env.API_HOST); //returns <http://127.0.0.1:58968>
//Act
const { result } = renderHook( () => useGetEventQuery({ id: '1cb9eb9e' }), {
wrapper: createWrapper,
});
await flush();
console.log(result.current.data);
// Assert: check the result
expect(result.current.data?.id).toBe(EXPECTED_BODY.id);
});
but still having the issue The following request was expected but not received
Any ideas what might be wrong? 😞Yousaf Nabi (pactflow.io)
Tatiana
09/27/2022, 2:09 PMimport { baseApi } from './baseApi';
import {
EventResponseSchema,
EventId,
} from './types';
export const eventsApi = baseApi
.enhanceEndpoints({ addTagTypes: ['Events'] })
.injectEndpoints({
endpoints: (builder) => ({
getEvent: builder.query<EventResponseSchema, { id: EventId }>({
query: ({ id }) => `events/${id}`,
providesTags: (result, error, { id }) => [{ type: 'Events', id }],
}),
}),
});
export const {
useGetEventQuery,
} = eventsApi;
Response schema is:
export interface EventResponseSchema {
id: string;
name: string;
teamId: string;
updatedAt: string;
createdAt: string;
duration?: number;
...
...
}
export type EventId = string;
baseApi
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/dist/query/react';
const apiHost = process.env.API_HOST;
export const baseApi = createApi({
reducerPath: 'services',
baseQuery: fetchBaseQuery({
baseUrl: apiHost ?? '/api',
mode: 'cors',
credentials: 'include',
}),
endpoints: () => ({}),
});
and by default we set process.env.API_HOST in the src/setupJestEnv.ts
process.env.API_HOST = '<http://localhost:8000>';Yousaf Nabi (pactflow.io)
const provider = new PactV3({
dir: path.resolve(process.cwd(), 'pacts'),
consumer: 'MyConsumer',
provider: 'MyProvider',
port: 8000
});
Also I don't think your request has completed, as the response object status 'isLoading: true' and isSuccess/isLoading is falseTatiana
09/27/2022, 2:20 PMwaitForNextUpdate to my request, such as
const { result, waitForNextUpdate } = renderHook( () => useGetEventQuery({ id: '1cb9eb9e' }), {
wrapper: createWrapper,
});
await waitForNextUpdate();
and now I am getting isLoading:false and the following error:
{
status: 'rejected',
endpointName: 'getEvent',
requestId: 'K3YytVNiG5C7LnhFAtr07',
originalArgs: { id: '1cb9eb9e' },
startedTimeStamp: 1664288258291,
error: {
status: 'FETCH_ERROR',
error: 'FetchError: request to <http://localhost:8000/events/1cb9eb9e> failed, reason: connect ECONNREFUSED ::1:8000'
},
isUninitialized: false,
isLoading: false,
isSuccess: false,
isError: true,
data: undefined,
currentData: undefined,
isFetching: false,
refetch: [Function: refetch]
}Tatiana
09/27/2022, 2:23 PMconsole.log(process.env.API_HOST); //returns <http://127.0.0.1:59891>
but error says the same as above:
error: {
status: 'FETCH_ERROR',
error: 'FetchError: request to <http://localhost:8000/events/1cb9eb9e> failed, reason: connect ECONNREFUSED ::1:8000'
},
I would expect the port would be different rather than 8000Tatiana
09/27/2022, 2:32 PMYousaf Nabi (pactflow.io)
Yousaf Nabi (pactflow.io)
Tatiana
09/27/2022, 2:50 PMhost for my provider setup? Like this:
const provider = new PactV3({
dir: path.resolve(process.cwd(), 'pacts'),
consumer: 'MyConsumer',
provider: 'MyProvider',
host: process.env.API_HOST
});
if so, should I use the following test setup then?
return provider.executeTest(async (mockserver) => {
//Arrange
process.env.API_HOST = mockserver.url;
console.log(process.env.API_HOST);Tatiana
09/27/2022, 3:17 PMYousaf Nabi (pactflow.io)
const provider = new PactV3({
dir: path.resolve(process.cwd(), 'pacts'),
consumer: 'MyConsumer',
provider: 'MyProvider',
port: 8000
});
you wont need this
process.env.API_HOST = mockserver.url;
console.log(process.env.API_HOST);Tatiana
09/27/2022, 5:00 PMerror: {
status: 'FETCH_ERROR',
error: 'FetchError: request to <http://localhost:8000/events/1cb9eb9e> failed, reason: connect ECONNREFUSED ::1:8000'
},
My tests looks like this now:
const provider = new PactV3({
dir: path.resolve(process.cwd(), 'pacts'),
consumer: 'MyConsumer',
provider: 'MyProvider',
port: 8000,
});
const EXPECTED_BODY = {
name: "test event dd",
id: "1cb9eb9e",
teamId: "dummy_tid",
};
function flush() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
function createWrapper({ children }: { children: React.ReactElement }) {
return <Provider store={makeStore()}>{children}</Provider>;
}
describe('GET /events/{id}', () => {
it('returns an event', async () => {
provider
.given('I can get an event')
.uponReceiving('a request for one event with the builder pattern')
.withRequest({
method: 'GET',
path: '/events/1cb9eb9e',
})
.willRespondWith({
status: 200,
body: EXPECTED_BODY,
});
return provider.executeTest(async () => {
//Act
const { result, waitForNextUpdate } = renderHook( () => useGetEventQuery({ id: '1cb9eb9e' }), {
wrapper: createWrapper,
});
await waitForNextUpdate();
console.log(result.current);
// Assert
expect(result.current.data?.id).toBe(EXPECTED_BODY.id);
});
});
});
any ideas why it doesn’t work? 😞Tatiana
09/27/2022, 6:40 PMprocess.env.API_HOST = '<http://127.0.0.1:8001>'; in the src/setupJestEnv.ts.
Thank you for your support and quick response! you helped me a lot! 🙌Timothy Jones
09/27/2022, 9:36 PMTatiana
09/27/2022, 9:55 PMTimothy Jones
09/27/2022, 10:03 PMTimothy Jones
09/27/2022, 10:05 PMTatiana
09/27/2022, 10:24 PM