mardi 20 février 2018

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".

Aucun commentaire:

Enregistrer un commentaire