Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

53
Views
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

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

Try this:

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

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.