如何在 Jest 中模拟插件

How to mock a plugin in Jest

我的单元测试设置不正确,这意味着我没有正确模拟导入的插件功能。

如何正确模拟我的 logData 函数?在插件中,函数 returns 未定义,可以选择。我只需要确保我 console.log 传递给它的任何内容。

我得到的当前错误是"Cannot spy the logData property because it is not a function; undefined given instead"

logData.js - 插件(只是 console.log 语句的包装器)

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

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

logData.spec.js - 我模拟了 localStorage 但我需要模拟插件 logData

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

class LocalStorageMock {
  constructor () {
    this.store = {}
  }
  getItem (key) {
    return this.store[key] || null
  }
  setItem (key, value) {
    this.store[key] = value.toString()
  }
  removeItem (key) {
    delete this.store[key]
  }
}

global.localStorage = new LocalStorageMock()

const localVue = createLocalVue()
const dataToLog = 'data to be logged'
localVue.use(logData)

const mockLogDataFunction = jest.spyOn(localVue.prototype, 'logData')

describe('logData plugin', () => {
  // PASSES
  it('adds a $logData method to the Vue prototype', () => {
    console.log(wrapper.vm.$logData)
    expect(Vue.prototype.$logData).toBeUndefined()
    expect(typeof localVue.prototype.$logData).toBe('function')
  })
  // Now passes
  it('[positive] console.logs data passed to it', () => {
    global.localStorage.setItem('isLoggingData', true)
    const spy = jest.spyOn(global.console, 'log')
    localVue.prototype.$logData('data to be logged')
    expect(spy).toHaveBeenCalledWith(dataToLog)
    // expect(mockLogDataFunction).toHaveBeenCalled()
    // console.log(localVue)
    // expect(localVue.prototype.$logData(dataToLog)).toMatch('data to be logged')
  })
  // PASSES
  it('[negative] does not console.log data passed to it', () => {
    const spy = jest.spyOn(global.console, 'log')
    global.localStorage.removeItem('isLoggingData')
    localVue.prototype.$logData(dataToLog)
    expect(spy).not.toHaveBeenCalled()

    // const spy = jest.spyOn(this.$logData, 'console')
    // expect(localVue.prototype.$logData(dataToLog)).toBe(und efined)
    // expect(spy).toBe(undefined)
  })
})

你做错了。

  1. jest.spyOn(object, methodName)。您需要将 localVue.prototype'logData' 作为参数传递,以跟踪是否调用了此方法。

Creates a mock function similar to jest.fn but also tracks calls to object[methodName]. Returns a Jest mock function.

  1. 检查方法是否被调用 – expect(spy).toHaveBeenCalled().

所以更改一些代码行:

const mockLogDataFunction = jest.spyOn(localVue.prototype, '$logData')
// invoke it and then ensure that that method is really called
localVue.prototype.$logData('foo')
expect(mockLogDataFunction).toHaveBeenCalled()