N
Nuxt2w ago
Yuri

mountSuspended & useCookie

Hello. Why my test show incorrect value for cookie? Log: Mock useCookie with value 0 Mock useCookie with value 1 locationConfirmationIsHidden (there isn't cookie): 1 locationConfirmationIsHidden (there is cookie): 1 Part of my component:
const locationConfirmationIsHidden = useCookie<number>(
CookieLocationConfirmationpIsHidden,
cookieGenerateOptionsClient(60 * 60 * 24 * 30, () => 0),
)
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
const locationConfirmationIsHidden = useCookie<number>(
CookieLocationConfirmationpIsHidden,
cookieGenerateOptionsClient(60 * 60 * 24 * 30, () => 0),
)
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
My test:
describe('LayoutHeaderLocation.vue', () => {
const createWrapper = async (initialState = { id: 1, canChange: true, title: 'Астрахань' }) => {
.....
return await mountSuspended(LayoutHeaderLocation);
};

beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
mockNuxtImport('useCookie', () => () => ({ value: 0 }));
});
it('there isn't cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 0');
return () => ({ value: 0 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (test куки нет):', wrapper.vm.locationConfirmationIsHidden?.value);
});

it('there is cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 1');
return () => ({ value: 1 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (there isnt't cookie):', wrapper.vm.locationConfirmationIsHidden?.value);

});
describe('LayoutHeaderLocation.vue', () => {
const createWrapper = async (initialState = { id: 1, canChange: true, title: 'Астрахань' }) => {
.....
return await mountSuspended(LayoutHeaderLocation);
};

beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
mockNuxtImport('useCookie', () => () => ({ value: 0 }));
});
it('there isn't cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 0');
return () => ({ value: 0 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (test куки нет):', wrapper.vm.locationConfirmationIsHidden?.value);
});

it('there is cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 1');
return () => ({ value: 1 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (there isnt't cookie):', wrapper.vm.locationConfirmationIsHidden?.value);

});
2 Replies
kapa.ai
kapa.ai2w ago
Hi @Yuri. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on the information provided in your question and the knowledge sources, I can offer some insights into why your test might be showing incorrect values for the cookie. The issue appears to be related to how you're mocking the useCookie composable in your tests. Let's break it down: 1. Mocking useCookie: You're using mockNuxtImport to mock the useCookie composable. This is the correct approach for mocking Nuxt's auto-imports in tests, as described in the Nuxt documentation (https://nuxt.com/docs/getting-started/testing#mocknuxtimport). 2. Multiple mocks in the same file: However, you're calling mockNuxtImport for useCookie multiple times in the same test file. As the documentation states:
mockNuxtImport can only be used once per mocked import per test file. It is actually a macro that gets transformed to vi.mock and vi.mock is hoisted, as described here (https://vitest.dev/api/vi.html#vi-mock).
This means that only the first mock (in your beforeEach block) is likely taking effect, and the subsequent mocks in your individual tests are not working as expected. 3. Solution: To change the mock implementation between tests, you should use vi.hoisted as suggested in the documentation (https://nuxt.com/docs/getting-started/testing#mocknuxtimport). Here's how you could modify your test:
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

const { useCookieMock } = vi.hoisted(() => {
return {
useCookieMock: vi.fn()
}
})

mockNuxtImport('useCookie', () => useCookieMock)

describe('LayoutHeaderLocation.vue', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
useCookieMock.mockReturnValue({ value: 0 });
});
it('there isn't cookie', async () => {
useCookieMock.mockReturnValue({ value: 0 });
// ... rest of your test
});

it('there is cookie', async () => {
useCookieMock.mockReturnValue({ value: 1 });
// ... rest of your test
});
});
import { vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'

const { useCookieMock } = vi.hoisted(() => {
return {
useCookieMock: vi.fn()
}
})

mockNuxtImport('useCookie', () => useCookieMock)

describe('LayoutHeaderLocation.vue', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
useCookieMock.mockReturnValue({ value: 0 });
});
it('there isn't cookie', async () => {
useCookieMock.mockReturnValue({ value: 0 });
// ... rest of your test
});

it('there is cookie', async () => {
useCookieMock.mockReturnValue({ value: 1 });
// ... rest of your test
});
});
This approach allows you to change the mock implementation between tests while still using mockNuxtImport correctly. Additionally, make sure you're using the latest version of Nuxt and its testing utilities, as there have been several fixes and improvements related to useCookie and testing, as evidenced by various pull requests (PR #25598 (https://github.com/nuxt/nuxt/pull/25598), PR #25255 (https://github.com/nuxt/nuxt/pull/25255)). If you're still experiencing issues after making these changes, you might want to consider using the refreshCookie utility to manually refresh the cookie value in your tests, as mentioned in the Nuxt documentation (https://nuxt.com/docs/api/utils/refresh-cookie). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@740173469404364872> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Want results from more Discord servers?
Add your server