我正在尝试测试在Vue组件的装载上是否调用了一个方法。对Vue和Typescript来说相当陌生。
export default class App extends Vue {
mounted () {
this.deviceId()
this.ipAddress()
this.channel()
this.show()
this.campaign()
this.adUnit()
}
这种方法有效,但我得到警告:
it('mounted methods are called', async () => {
const deviceId = jest.fn()
wrapper = shallowMount(App, {
methods: {
deviceId
}
})
expect(deviceId).toHaveBeenCalled()
})
错误:
console.error node_modules/@vue/test-utils/dist/vue-test-utils.js:1735
[vue-test-utils]: overwriting methods via the `methods` property is deprecated and will be removed in the next major version. There is no clear migration path for the `methods` property - Vue does not support arbitrarily replacement of methods, nor should VTU. To stub a complex method extract it from the component and test it in isolation. Otherwise, the suggestion is to rethink those tests.
我尝试过使用jest spyOn,但找不到访问该方法的方法;
const spy = jest.spyOn(App.prototype, 'methodName')
wrapper = shallowMount(App)
expect(spy).toHaveBeenCalled()
给出以下错误:
Cannot spy the deviceId property because it is not a function; undefined given instead
以下也不起作用:
const spy = jest.spyOn(App.methods, 'methodName')
错误:
Property 'methods' does not exist on type 'VueConstructor<Vue>'.ts(2339)
以及以下内容:
const spy = jest.spyOn(App.prototype.methods, 'deviceId')
错误:
Cannot spyOn on a primitive value; undefined given
我读过一些地方,我可能需要为组件定义一个接口,但我不确定这是如何在内部定义函数的,或者是否有必要?
我几天来一直面临同样的问题,但我找到了在调用jest.spyOn()
时指向正确方法的方法。
这有点棘手,但你会发现你的类的方法是这样的:
const spy = jest.spyOn(App.prototype.constructor.options.methods, 'deviceId');
请注意(即使这看起来很明显,以防万一(,在包装组件之前,您需要执行操作,例如:
const spy = jest.spyOn(App.prototype.constructor.options.methods, 'deviceId');
wrapper = mount(App, { /* Your options go here */ });
顺便说一下,您不需要在选项中定义methods属性。
在属性methods
下定义方法。只有这样,您才能从类中访问它们。
export default class App extends Vue {
methods: {
deviceId(){
console.log("do your stuff")
}
}
}
有关methods
用法的更多示例,请参阅此处