我的单元测试没有正确设置,这意味着我没有正确模拟导入的插件功能。
如何正确模拟logData
函数?在插件中,该函数返回undefined,这是由您选择的。我只需要确保我console.log
传递给它的任何内容即可。
我得到的当前错误是“由于无法监视logData属性,因为它不是一个函数;给定为undefined”
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)
})
})
答案 0 :(得分:1)
您做错了事。
jest.spyOn(object, methodName)
。您需要传递var project = methodReturnsOptional();
boolean ret = project.isPresent() && project.get().getDocIds().remove(docId);
和localVue.prototype
作为参数,以跟踪是否调用了此方法。创建类似于
'logData'
的模拟函数,但也跟踪对jest.fn
。返回一个Jest模拟函数。
object[methodName]
。因此更改代码的几行:
expect(spy).toHaveBeenCalled()
const mockLogDataFunction = jest.spyOn(localVue.prototype, '$logData')