Test a Mock Router with composition API adn Vitest #1728
Answered
by
freakzlike
joseluisgs
asked this question in
Q&A
-
Hi This is my component <button
data-testid="DayButton"
class="btn btn-primary"
@click="goToDaybook()"
>
DayBook
</button> <script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const goToDaybook = () => router.push({ name: 'daybook-no-entry' })
const goToAbout = () => router.push({ name: 'about' })
</script> Here it is my test test('should be go to a daybook-no-entry', async () => {
vi.mock('vue-router', () => ({
useRoute: vi.fn(),
useRouter: vi.fn(() => ({
push: () => {},
})),
}))
const push = vi.fn()
useRouter.mockImplementationOnce(() => ({
push,
}))
const wrapper = mount(HomeView)
// Mock del metodo goToDayBook
wrapper.vm.goToDaybook = vi.fn()
// Trabajamos con el boton
const dayButton = wrapper.find('[data-testid="DayButton"]')
expect(dayButton.exists()).toBe(true)
// texto de boton es daybook
expect(dayButton.text()).toBe('DayBook')
await dayButton.trigger('click')
// Cone sto ya sabemos que lo ha llamado!!!
expect(wrapper.vm.goToDaybook).toHaveBeenCalledTimes(1)
// Router push ha sido llamado
expect(push).toHaveBeenCalled()
}) But I have the following error FAIL tests/unit/views/HomeViewTest.spec.js > View -> HomeView > Hacer click en el botón debe redireccionar a daybook-no-entry
AssertionError: expected "spy" to be called at least once
❯ tests/unit/views/HomeViewTest.spec.js:41:18
39| expect(wrapper.vm.goToDaybook).toHaveBeenCalledTimes(1)
40| // Router push ha sido llamado
41| expect(push).toHaveBeenCalled()
| ^
42| })
43| }) Could you help me or gieve some guide? Thank you |
Beta Was this translation helpful? Give feedback.
Answered by
freakzlike
Aug 19, 2022
Replies: 1 comment 5 replies
-
You overwrite your method with |
Beta Was this translation helpful? Give feedback.
5 replies
Answer selected by
joseluisgs
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You overwrite your method with
wrapper.vm.goToDaybook = vi.fn()
. So it will no longer do it's normal logic (callingrouter.push
). Remove the check ofwrapper.vm.goToDaybook
and try again