简体   繁体   中英

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

Try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM