[Vuejs]-Vues.js unit test mutations: cannot complete testing of function

0👍

the solution is to use lolex package ( JavaScript implementation of the timer APIs)

npm install --save-dev lolex

and then in my spec file to fake the timer functions
1 – using lolex

 var lolex = require('lolex')

2 – creating a clock

describe('mutations', () => {
  let state
  let clock

  beforeEach(() => {
    clock = lolex.createClock()
    state = {}
    ....

3 – test the switch from Working -> Rest period after 10 sec
( working, resting time are defined in the config.js file imported into the mutation.js. I have to shorten them for testing purposes … maybe it’s possible to define a specific config.test.js file ??)

using the clock.setTimeout(callback, delay) … so the tick(state) function of the mutation.js is called… it must be exported/imported before

  describe('TOGGLE WORKING->REST', () => {
    it('should switch to REST period after 5 sec', () => {
      state.isWorking = true
      state.soundEnabled = true
      state.interval = clock.setInterval(() => tick(state), 1000)
      mutations[types.START](state)
      expect(Vue.noise.start).to.have.been.called
      state.counter = 0
      // delay clock
      clock.setTimeout(() => {
        expect(state.isWorking).to.equal(false)
      }, 5000)
    })
  })

4 – Test the switch from Rest -> Working period, using a click.tick() before the timeOut() to change the state from Working -> Rest just before

 it('should switch back to WORK period after 10 sec', () => {
    state.isWorking = true
    state.soundEnabled = true
    state.interval = clock.setInterval(() => tick(state), 1000)
    mutations[types.START](state)
    expect(Vue.noise.start).to.have.been.called
    state.counter = 0
    clock.tick(5000) // switch to REST period
    // delay clock
    clock.setTimeout(() => {
      expect(state.isWorking).to.equal(false)
    }, 5000)
  })

et voilà… thanks to lolex ..

Leave a comment