Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Mocking vue-router's push() method in Unit testing - Vue 3

I'm new to Vue and StackOverflow, but I'll try to explain my problem.

I get a TypeError when I try to run the unit test for my application.

"TypeError: Cannot read properties of undefined (reading 'push')"

https://i.stack.imgur.com/pqUkZ.png

The program runs exactly as it should otherwise, it's only the test that fails.

The test tries to run $router.push in the application, but can't, because it doesn't know what that is, how can I successfully mock the push method while testing?

My example.spec.js test code looks like this:

import { shallowMount } from '@vue/test-utils'
import LoginView from '@/views/LoginView.vue'

describe('LoginView.vue', () => {
  it('loginSuccess-test', async () => {

    const wrapper = shallowMount(LoginView, {
      mocks: {
        $router: {
          push: () => {}
        }
      }
    })

    await wrapper.setData({username:'user', password:'pass'})
    await wrapper.find('button').trigger('click')
    const statusId = wrapper.find('#loginstatusLabel');

    expect(wrapper.find('#loginstatusLabel').element.textContent).toBe('true')

  })
})

My LoginView.vue methods code looks like this:

  methods: {
    checkCredentials() {
      if (this.username === 'user' && this.password === 'pass') {
        this.loginSuccess = 'true';
        this.$router.push({ name: 'home' });
      }
      else {
        this.toast.error("Username or password is incorrect    Try again");
        this.message = 'Login failed!';
        this.isActive = false;

      }
    }
</script>

I'm trying to make the push method redirect the user to "home" when he successfully logs in and mock the redirection in testing.

Any help will be greatly appreciated

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this:

mocks: {
        $router: {
          push: jest.fn(),
        }
      }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda