1

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.sstatic.net/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

2 Answers 2

1

In vue3 you need to wrap the mocks property inside global property

Vue2

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

Vue3

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

Source: https://test-utils.vuejs.org/guide/advanced/vue-router.html

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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

1 Comment

I've already tried that, but the same TypeError gets thrown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.