T
TanStack3y ago
optimistic-gold

React Query Test with MSW - useMutation test returns `undefined` for current.data property

https://codesandbox.io/s/great-wood-whq7z5?file=/src/hooks.spec.tsx I am basically copying the implementation from this repo (https://github.com/TkDodo/testing-react-query) and writing a test for useMutation. Taking inspiration from this tutorial (https://www.js-howto.com/react-query-usemutation-with-jest-testing/) When I run the test, current.data is undefined. Why? hooks.spec.tsx
test("creates new contact", async () => {
const { result } = renderHook(() => useAddContact(), {
wrapper: createWrapper()
});

act(() => {
result.current.mutate({
first_name: "Job",
last_name: "Bones"
});
});

await waitFor(() => {
console.log("result.current", result.current);
return result.current.isSuccess;
});

expect(result.current.isSuccess).toBe(true);
});
test("creates new contact", async () => {
const { result } = renderHook(() => useAddContact(), {
wrapper: createWrapper()
});

act(() => {
result.current.mutate({
first_name: "Job",
last_name: "Bones"
});
});

await waitFor(() => {
console.log("result.current", result.current);
return result.current.isSuccess;
});

expect(result.current.isSuccess).toBe(true);
});
msw handler
rest.post("/api/contacts#new", (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
first_name: "Job",
last_name: "Bones"
})
);
})
rest.post("/api/contacts#new", (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
first_name: "Job",
last_name: "Bones"
})
);
})
mutation
type NewContactPayload = {
first_name: string;
last_name?: string;
};

export const useAddContact = () => {
return useMutation({
mutationFn: (newContact: NewContactPayload) =>
axios({
url: "/api/contacts#new",
method: "POST",
data: newContact
}).then(res => res.data)
});
};
type NewContactPayload = {
first_name: string;
last_name?: string;
};

export const useAddContact = () => {
return useMutation({
mutationFn: (newContact: NewContactPayload) =>
axios({
url: "/api/contacts#new",
method: "POST",
data: newContact
}).then(res => res.data)
});
};
rostgoat
CodeSandbox
great-wood-whq7z5 - CodeSandbox
great-wood-whq7z5 by rostgoat using @tanstack/react-query, @testing-library/jest-dom, @testing-library/react, @types/jest, axios, express, jest, jest-environment-jsdom, loader-utils
GitHub
GitHub - TkDodo/testing-react-query
Contribute to TkDodo/testing-react-query development by creating an account on GitHub.
user
JS-HowTo
React-Query useMutation with Jest Testing | JS-HowTo
React-Query useMutation hook with Jest and React-testing-library for testing the UI components and the hooks. Complete full-stack example.
2 Replies
optimistic-gold
optimistic-goldOP3y ago
I am able to get the tests to pass if I use a dummy component that calls the mutation but not act. Why? Here is what I used to get the tests to pass: spec
const mockedAlert = jest.fn();
global.alert = mockedAlert;

describe('Mutation', () => {
test("adds contacts", async () => {
const user = userEvent.setup();
const result = renderWithClient(<ExampleMutation />);

const btn = result.getByText("Add Contact");

await user.click(btn);

await waitFor(() => {
expect(mockedAlert).toHaveBeenCalledWith("success");
});
});
})
const mockedAlert = jest.fn();
global.alert = mockedAlert;

describe('Mutation', () => {
test("adds contacts", async () => {
const user = userEvent.setup();
const result = renderWithClient(<ExampleMutation />);

const btn = result.getByText("Add Contact");

await user.click(btn);

await waitFor(() => {
expect(mockedAlert).toHaveBeenCalledWith("success");
});
});
})
ExampleMutation
export function ExampleMutation() {
const {mutate} = useAddContact();


const onAddContact = () => {
mutate({
first_name: "Job",
last_name: "Bones"
}, {
onSuccess:() => {
console.log('success')
alert('success')
},
onError:() => {
console.log('error')
alert('error')
}
});

}
return (
<button onClick={onAddContact}>Add Contact</button>
)
}
export function ExampleMutation() {
const {mutate} = useAddContact();


const onAddContact = () => {
mutate({
first_name: "Job",
last_name: "Bones"
}, {
onSuccess:() => {
console.log('success')
alert('success')
},
onError:() => {
console.log('error')
alert('error')
}
});

}
return (
<button onClick={onAddContact}>Add Contact</button>
)
}
foreign-sapphire
foreign-sapphire3y ago
I'm also having trouble trying to create tests for useMutation. I'm doing almost the same as you, but isSuccess always returns false cc: @Maintainer - Query

Did you find this page helpful?