Search code examples
javascriptvue.jsvue-test-utils

Unit testing a Vue plugin


I have a plugin that console.logs data.

logData.spec.js

import Vue from 'vue'
import { createLocalVue } from '@vue/test-utils'
import logData from './logData'

describe('logData plugin', () => {
  const localVue = createLocalVue()
  it('adds a $logData method to the Vue prototype', () => {
    expect(Vue.prototype.$logData).toBeUndefined()
    localVue.use(logData)
    expect(typeof localVue.prototype.$logData).toBe('function')
  })
  it('console.logs data passed to it', () => {
    const data = 'data to be logged'
    const localVue = createLocalVue()
    localVue.use(logData)
    expect(localVue.prototype.$logData(data)).toBe('data to be logged')
  })
})

logData.js

export function logData (dataToLog) {
  const isLoggingData = localStorage.getItem('isLoggingData')
  if (isLoggingData) {
    console.log(dataToLog)
  }
}

export default {
  install: function (Vue) {
    Vue.prototype.$logData = logData
  }
}

The error I get is in my unit test is Expected: 'data to be logged", Received: undefined. Why is the second test being read as undefined?


Solution

  • It's expected behavior since console.log() returns undefined. To get desired result you should add this line of code to your lodData function:

    return dataToLog
    
    export function logData (dataToLog) {
      const isLoggingData = localStorage.getItem('isLoggingData')
      if (isLoggingData) {
        console.log(dataToLog)
        return dataToLog
      }
    }
    

    NOTICE: Also you don't have localStorage in your test environment.