N
Nuxt4w ago
Leo

Vitest times out when mocking the Router

Hey, I'm currently trying to mock useRouter().push(), but unfortunately, Vitest (the mountSuspended function) times out.
// Some stuff
const mockRouterPush = vi.fn();

mockNuxtImport('useRouter', () => {
return () => ({
push: mockRouterPush,
});
});

describe('CreateDaytisticContent', () => {
beforeEach(() => {
vi.clearAllMocks();
// Setup successful API response
mockCreateDaytistic.mockResolvedValue({
status: 201,
_data: { id: '123' },
});
});

it('submits form successfully when date is selected', async () => {
const wrapper = await mountSuspended(CreateDaytisticContent);
const testDate = new Date('2024-01-01');

// First, set the modelValue prop
await wrapper.findComponent(DatePicker).setValue(testDate);

// Then emit the update event
await wrapper.findComponent(DatePicker).vm.$emit('update', testDate);

// Wait for Vue to process the updates
await wrapper.vm.$nextTick();

// Trigger form submission
await wrapper.find('form').trigger('submit');

// Wait for all promises to resolve
await flushPromises();

// Verify API call was made with correct date
expect(mockCreateDaytistic).toHaveBeenCalledWith(testDate);

// Verify success flow
expect(mockRouterPush).toHaveBeenCalled();
expect(mockSuccess).toHaveBeenCalled();
});


});
// Some stuff
const mockRouterPush = vi.fn();

mockNuxtImport('useRouter', () => {
return () => ({
push: mockRouterPush,
});
});

describe('CreateDaytisticContent', () => {
beforeEach(() => {
vi.clearAllMocks();
// Setup successful API response
mockCreateDaytistic.mockResolvedValue({
status: 201,
_data: { id: '123' },
});
});

it('submits form successfully when date is selected', async () => {
const wrapper = await mountSuspended(CreateDaytisticContent);
const testDate = new Date('2024-01-01');

// First, set the modelValue prop
await wrapper.findComponent(DatePicker).setValue(testDate);

// Then emit the update event
await wrapper.findComponent(DatePicker).vm.$emit('update', testDate);

// Wait for Vue to process the updates
await wrapper.vm.$nextTick();

// Trigger form submission
await wrapper.find('form').trigger('submit');

// Wait for all promises to resolve
await flushPromises();

// Verify API call was made with correct date
expect(mockCreateDaytistic).toHaveBeenCalledWith(testDate);

// Verify success flow
expect(mockRouterPush).toHaveBeenCalled();
expect(mockSuccess).toHaveBeenCalled();
});


});
2 Replies
kapa.ai
kapa.ai4w ago
Hi @Leo. 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 the knowledge sources, I can offer some insights into your issue with Vitest timing out when mocking the Router. The problem you're experiencing is likely related to how you're mocking the useRouter composable. While your approach of using mockNuxtImport is correct, there might be some issues with how the test is set up or how the component interacts with the router. Here are some suggestions to help resolve the timeout issue: 1. Ensure you're using the latest version of @nuxt/test-utils. The Nuxt documentation on testing (https://nuxt.com/docs/getting-started/testing#unit-testing) recommends using @nuxt/test-utils/runtime for importing test utilities. 2. Instead of mocking useRouter directly, you might want to try mocking the entire #imports module. This approach is mentioned in a Stack Overflow post (https://stackoverflow.com/questions/78427333) about mocking Supabase in Vitest:
vi.mock('#imports', () => {
return {
useRouter: () => ({
push: vi.fn(),
}),
};
});

vi.mock('#imports', () => {
return {
useRouter: () => ({
push: vi.fn(),
}),
};
});

3. If you're still experiencing timeouts, you might need to adjust the timeout settings for your tests. The Nuxt documentation on testing setup (https://nuxt.com/docs/getting-started/testing#setup) mentions a setupTimeout option that you can use:
await setup({
setupTimeout: 60000, // Increase this value if needed
})

await setup({
setupTimeout: 60000, // Increase this value if needed
})

4. Make sure you're not accidentally triggering any real navigation in your component that could cause the test to hang. The Nuxt router documentation (https://nuxt.com/docs/api/composables/use-router) recommends using navigateTo instead of router.push() for programmatic navigation. 5. If you're using mountSuspended, ensure that all async operations in your component setup are properly awaited. The Nuxt testing documentation (https://nuxt.com/docs/getting-started/testing#mountsuspended) shows that mountSuspended allows for async setup. If these suggestions don't resolve the issue, you might need to provide more context about your component and how it's using the router. It's possible that there's an interaction between your component and the router that's causing the timeout, which isn't immediately apparent from the test code you've shared. Remember, when working with Nuxt and Vitest, it's important to ensure that all your dependencies are up-to-date and that you're following the latest best practices for testing Nuxt applications. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4w ago
<@809685585374740480> 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