Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL redirection testing with Vue.js and Jest

I'm trying to write a test to checks that when the user clicks on "login" button, the URL is redirected to /auth/. Frontend is written with Vue.js and testing is done with Jest.

Here is how the Vue component redirects (from UserLogged.vue). It works in the browser.

export default {
  name: 'UserLogged',
  props: ['userName'],
  methods: {
    login: function (event) {
      window.location.href = '/auth/'
    }
  }
}

and here is the attempt to test it :

import Vue from 'vue'
import UserLogged from '@/components/UserLogged'

describe('UserLogged.vue', () => {
  it('should redirect anonymous users to /auth/ when clicking on login button', () => {
    const Constructor = Vue.extend(UserLogged)
    const vm = new Constructor().$mount()
    const button = vm.$el.querySelector('button')
    // Simulate click event
    // Note: the component won't be listening for any events, so we need to manually run the watcher.
    const clickEvent = new window.Event('click')
    button.dispatchEvent(clickEvent)
    vm._watcher.run()
    expect(window.location.href).toEqual('http://testserver/auth/')
  })
})

Test output gives "http://testserver/" instead of expected "http://testserver/auth".

like image 582
samb Avatar asked Feb 05 '23 01:02

samb


1 Answers

I could make the test run nicely with some help https://forum.vuejs.org/t/url-redirection-testing-with-vue-js-and-jest/28009/2

Here is the final test (now written with @vue/test-utils lib) :

import {mount} from '@vue/test-utils'
import UserLogged from '@/components/UserLogged'

describe('UserLogged.vue', () => {
  it('should redirect anonymous users to /auth/ when clicking on login button', () => {
    const wrapper = mount(UserLogged)
    const button = wrapper.find('button')
    window.location.assign = jest.fn() // Create a spy
    button.trigger('click')
    expect(window.location.assign).toHaveBeenCalledWith('/auth/');
  })
})

BTW, I had to change window.location.href = '/auth/' to window.location.assign('/auth/') in components/UserLogged.vue.

like image 138
samb Avatar answered Feb 12 '23 14:02

samb