CFHxKai
CFHxKai
NNuxt
Created by CFHxKai on 11/11/2024 in #❓・help
How can I know how much times a method inside the mocked composable was called in a test?
Hi. 😄 I'm trying to learn about tests in Nuxt but is a little hard to find content/courses about it. I have something like this:
import { describe, it, expect, vi } from 'vitest';
import {
mountSuspended,
mockNuxtImport,
} from '@nuxt/test-utils/runtime';
import { CustomBtn } from '#components';

const { useMyComposableMock } =
vi.hoisted(() => {
return {
useMyComposableMock : vi.fn(() => ({
myMethod: vi.fn(),
})),
};
});

describe('Component CustomBtn', async () => {
it('should call 4 times myMethod', async () => {
const component = await mountSuspended(CustomBtn);

const button = component.find('button');

await button.trigger('click');
await button.trigger('click');
await button.trigger('click');
await button.trigger('click');

expect(useMyComposableMock).toHaveBeenCalledTimes(4);
});
});
import { describe, it, expect, vi } from 'vitest';
import {
mountSuspended,
mockNuxtImport,
} from '@nuxt/test-utils/runtime';
import { CustomBtn } from '#components';

const { useMyComposableMock } =
vi.hoisted(() => {
return {
useMyComposableMock : vi.fn(() => ({
myMethod: vi.fn(),
})),
};
});

describe('Component CustomBtn', async () => {
it('should call 4 times myMethod', async () => {
const component = await mountSuspended(CustomBtn);

const button = component.find('button');

await button.trigger('click');
await button.trigger('click');
await button.trigger('click');
await button.trigger('click');

expect(useMyComposableMock).toHaveBeenCalledTimes(4);
});
});
This is called one time, and I think this is right because composable is instantiated one time, but how can I get how much times the method myMethod is called. For example inside the component file I have something like this:
<script setup lang="ts">
const { myMethod } = useMyComposable();

const handleMyBtnClick = async () => {
myMethod(someParams);
}
</script>

<template>
<button @click="hadleMyBtnClick">Click Here</button>
</template>
<script setup lang="ts">
const { myMethod } = useMyComposable();

const handleMyBtnClick = async () => {
myMethod(someParams);
}
</script>

<template>
<button @click="hadleMyBtnClick">Click Here</button>
</template>
And how can I get how much times method (handleMyBtnClick) inside de component who is handle this clicks are called? Thank you so much... 😉
11 replies
NNuxt
Created by CFHxKai on 10/23/2024 in #❓・help
How to prevent navigation in nested routes?
I have a route like /[firstId]/[secondId]. The page [firstId] has a list of links to navigate and a <NuxtPage /> to load a page with the form from secondId data, but before change between nested secondId's routes I'm checking if the form is dirty and trying to prevent navigation asking to user if he really wants to leave and lost the changes. But in nested page the onBeforeRouteLeave don`t work. There is another way to achieve this? Thank you 👍
6 replies