As a newcomer to Vue and StackOverflow, I wanted to share my issue.
While attempting to run the unit test for my application, I encountered a TypeError.
The error message stated: "TypeError: Cannot read properties of undefined (reading 'push')"
You can view the error here: https://i.sstatic.net/pqUkZ.png
The program functions correctly otherwise; it is only the test that fails.
The test attempts to execute $router.push in the application but cannot do so because it does not recognize what that is. How can I effectively mock the push method during testing?
This is an excerpt from my example.spec.js test code:
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')
})
})
Here's how the methods section in my LoginView.vue file is structured:
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 am aiming to redirect the user to "home" upon successful login using the push method and simulate the redirection during testing.
Any assistance on this matter would be greatly appreciated.