1

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?

2
  • What's logData file look like? Commented Aug 20, 2019 at 17:26
  • @danronmoon, Added file. Commented Aug 20, 2019 at 17:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Yes, the "global coverage for branches is below 95%" means I need to test if the localStorage property exists. I guess I just need to add a localStorage object to the second test and check if 'isLoggingData' exists?
You need to mock it. medium.com/3yourmind/…
I'm lost on this
@Javas The return value of console.log is not relevant, since nothing is returned at all (which is the actual cause of undefined in this case).
@tony19, Yes, in that case it is. But if he manages to mock the localStorage, this line will help him to pass his test.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.