i am trying to test a custom hook which is using subscribe to more of apollo client. the custom hook is fetching events and it is connected with subscription to the subscribe to more apollo client option to add more events to the cached query result ( using apollo client type policy} Im receiving the following error:
Expected variables: {"limit":10,"offset":0,"exclude":{"eventType":["LEAKAGE","WATCHMAN"]},"filter":{"shipId":<undefined>,"cameraId":<undefined>,"companyId":<undefined>,"fleetId":1,"withHidden":<undefined>}}
Failed to match 1 mock for this query. The mocked response had the following variables:
{"exclude":{"eventType":["WATCHMAN","LEAKAGE"]},"filter":{"fleetId":1,"shipId":1,"cameraId":1,"companyId":1,"withHidden":false},"limit":10,"offest":0,"withHidden":true}
here are the relevant files:
the fetch events hook:
export const useFetchShipEvents = ({
limit,
offset = 0,
fleetId,
shipId,
cameraId,
companyId,
noExclude = false,
withHidden,
}: IProps) => {
const [shipEvents, setShipEvents] = useState<ShipEvents>();
const [isEventsLoading, setIsEventsLoading] = useState(false);
const [isEventsError, setIsEventsError] = useState<ApolloError>();
const user = useReactiveVar(userStore.userAuth.authUser);
console.log(' ~ file: fetchEvents.hooks.ts:34 ~ user:', user);
const userAdmin = useReactiveVar(userStore.userAuth.userAdmin);
let groupedShipIds = user?.attributes?.['custom:grouped_Shipid'];
if (groupedShipIds) {
groupedShipIds = JSON.parse(groupedShipIds);
}
const [fetchEvents, { subscribeToMore, loading, fetchMore }] = useLazyQuery<any, EventsPaginationInput>(
queries.events,
{
variables: {
limit,
offset,
exclude: noExclude
? { eventType: [ShipEventType.WATCHMAN] }
: {
eventType: [ShipEventType.LEAKAGE, ShipEventType.WATCHMAN],
},
filter: {
shipId,
cameraId,
companyId,
fleetId,
withHidden,
},
},
fetchPolicy: 'cache-and-network',
partialRefetch: true,
returnPartialData: true,
onCompleted(data) {
setShipEvents(data?.shipEvents);
},
onError(error) {
console.error(error);
},
}
);
useEffect(() => {
if (!shipEvents && loading) {
setIsEventsLoading(true);
}
return () => setIsEventsLoading(false);
}, [loading]);
useEffect(() => {
if (subscribeToMore && (fleetId || shipId || userAdmin)) {
subscribeToMore({
document: subscriptions.eventAdded,
variables: {
fleetId,
shipId,
groupedShipIds: groupedShipIds,
exclude: { eventType: [ShipEventType.LEAKAGE, ShipEventType.WATCHMAN] },
},
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData) return prev;
const event = subscriptionData.data.shipEventAdded;
const prevEventsArr = prev.shipEvents.events;
const isSome = prevEventsArr.some((prevEvents: ShipEvent) => prevEvents.id === event.id);
if (isSome) return;
return Object.assign({}, prev, {
shipEvents: { events: [event, ...prev.shipEvents.events], totalCount: prev.totalCount + 1 },
});
},
});
}
}, [subscribeToMore, fleetId, shipId, cameraId]);
return { fetchEvents, shipEvents, isEventsLoading, fetchMore, subscribeToMore };
};
the mock:
export const shipEventsMockQuery = [
{
request: {
query: GET_EVENTS,
variables: {
exclude: { eventType: ['WATCHMAN', 'LEAKAGE'] },
filter: { fleetId: 1, shipId: 1, cameraId: 1, companyId: 1, withHidden: false },
limit: 10,
offest: 0,
withHidden: true,
},
},
result: {
data: {
shipEvents: {
events: [
{
burnedImage1Url: null,
burnedImage2Url: null,
burnedVodUrl: null,
camera: {
id: 1290,
shipId: 1,
shipCameraId: 4,
location: null,
description: null,
title: '4',
},
cameraId: 1290,
endTime: null,
eventState: 'NOT_ACKNOWLEDGED',
eventType: 'PPE_HELMET',
id: 58028,
image1Url: null,
image2Url: null,
isCameraDisabled: false,
lastPersonTime: null,
liveUrl: null,
notes: null,
recordingStartTime: null,
severity: 'INTERMEDIATE',
shipEventId: 423421342,
shipId: 1,
speed: null,
startTime: '2023-03-10T06:26:30.706Z',
vodHlsUrl: null,
vodPath: null,
__typename: 'ShipEvent',
},
],
totalCount: 1,
},
},
},
},
];
export const shipEventsSubscriptionmock = [
{
request: {
query: subscriptions.eventAdded,
variables: {
exclude: { eventType: ['WATCHMAN', 'LEAKAGE'] },
shipId: 1,
fleedId: 1,
groupedShipIds: [1, 2],
withHidden: true,
},
},
result: {
data: {
eventAdded: [
{
burnedImage1Url: null,
burnedImage2Url: null,
burnedVodUrl: null,
camera: {
id: 1290,
shipId: 1,
shipCameraId: 4,
location: null,
description: null,
title: '4',
},
cameraId: 1290,
endTime: null,
eventState: 'NOT_ACKNOWLEDGED',
eventType: 'PPE_HELMET',
id: 58028,
image1Url: null,
image2Url: null,
isCameraDisabled: false,
lastPersonTime: null,
liveUrl: null,
notes: null,
recordingStartTime: null,
severity: 'INTERMEDIATE',
shipEventId: 423421342,
shipId: 1,
speed: null,
startTime: '2023-03-10T06:26:30.706Z',
vodHlsUrl: null,
vodPath: null,
__typename: 'ShipEvent',
},
],
},
},
},
];
the test:
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: jest
.fn()
.mockReturnValue({ shipId: '8', modeId: '2377', cameraId: '12097', shipCameraId: '21' }),
}));
const mocks = [...shipEventsMockQuery, ...shipEventsSubscriptionmock];
function getHookWrapper(mocks = []) {
const wrapper = ({ children }) => (
<MockedProvider mocks={mocks} addTypename={false}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(() => useFetchShipEvents({ limit: 10, fleetId: 1 }), {
wrapper,
});
return { result, waitForNextUpdate };
}
describe('shipEvents', () => {
it('test1', async () => {
const { result, waitForNextUpdate } = getHookWrapper(mocks);
await act(async () => {
result.current.fetchEvents();
console.log(' ~ file: ShipEventsTest.test.js:61 ~ describe ~ result:', result.current);
await waitFor(() => expect(result.current.isEventsLoading).toBeTruthy(), {
timeout: 2000,
});
});
expect(result.current?.shipEvents?.events?.length)?.toBeGreaterThanOrEqual(1);
});
});
thanks for the guidance.