Reputation: 1
I've been struggling with some tests for some time and I cannot find a proper way to make them work.
I use vitest, vue-testing-library and jest-dom when useful.
What I want is to be able to use different mocked data for different tests and I cannot find a way to do that. If I use the same stuff in a beforeEach() loop
beforeEach(() => {
useQuery1.mockResolvedValue({
data1: {
amount: 0,
date: '2021-01-01',
},
data2: { amount: 0 },
data3: { amount: 0 },
data4: { amount: 0 },
data5: {
total: 0,
url: 'https://www.google.com',
},
})
}
it works fine but that's not what I want.
Here's a simplified sample of my test file:
vi.mock('@/dashboard/queries/useQuery1')
describe('Widget1', () => {
beforeEach(() => {
// Reset the mock before each test
useDivisionWidgetsQuery.mockReset()
})
test('test 1', async () => {
useQuery1.mockResolvedValueOnce({
data1: {
amount: 0,
date: '2021-01-01',
},
data2: { amount: 0 },
data3: { amount: 0 },
data4: { amount: 0 },
data5: {
total: 0,
url: 'https://www.google.com',
},
})
render(Widget1, {
props: props,
})
const futureTitle = screen.getByText('Future')
expect(futureTitle).toBeInTheDocument()
})
test('test 2', async () => {
useQuery1.mockResolvedValueOnce({
data1: null, // different data
data2: { amount: 0 },
data3: { amount: 0 },
data4: { amount: 0 },
data5: {
total: 0,
url: 'https://www.google.com',
},
})
render(Widget1, {
props: props,
})
const futureTitle = screen.getByText('Future')
expect(futureTitle).not.toBeInTheDocument()
})
})
Separately the tests work fine but the issue is related to vi.mock() I guess.
The error message is the following :
This error originated in "assets/tests/vitest/components/Widget1.spec.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
It seems that there a many, many ways to mock the stuff we want and I already spent hours looking for answers here and nothing has been working so far.
Thanks in adance.
Upvotes: 0
Views: 901
Reputation: 1
What you can do is something like this
const mocks = vi.hoisted(() => ({
useQuery1: vi.fn(),
}));
vi.mock('@/dashboard/queries/useQuery1', () =>({
useQuery1: mocks.useQuery1,
}));
and then in your tests, you could mocks.useQuery1.mockResolvedValue(...)
For more information, check this https://vitest.dev/api/vi#vi-hoisted
Upvotes: 0