javascript - Testmetod kallad i mounted-hook Vue klasskomponent typescript
Jag försöker testa att en metod kallas vid montering av en Vue-komponent. Ganska ny på Vue och Typescript.
export default class App extends Vue {
mounted () {
this.deviceId()
this.ipAddress()
this.channel()
this.show()
this.campaign()
this.adUnit()
}
detta tillvägagångssätt fungerar men jag får en varning:
it('mounted methods are called', async () => {
const deviceId = jest.fn()
wrapper = shallowMount(App, {
methods: {
deviceId
}
})
expect(deviceId).toHaveBeenCalled()
})
Felet:
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.
Jag har försökt använda jest spyOn, men jag kan inte hitta ett sätt att komma åt metoden;
const spy = jest.spyOn(App.prototype, 'methodName')
wrapper = shallowMount(App)
expect(spy).toHaveBeenCalled()
Ger följande fel:
Cannot spy the deviceId property because it is not a function; undefined given instead
Följande fungerar inte heller:
const spy = jest.spyOn(App.methods, 'methodName')
Fel :
Property 'methods' does not exist on type 'VueConstructor<Vue>'.ts(2339)
Och följande:
const spy = jest.spyOn(App.prototype.methods, 'deviceId')
Fel :
Cannot spyOn on a primitive value; undefined given
Jag har läst på vissa ställen att jag kanske behöver definiera ett gränssnitt för komponenten, men jag är inte säker på hur detta fungerar med att definiera funktioner inuti eller om det är nödvändigt.
Svar #1
Jag har stött på samma problem i några dagar, men jag har hittat sättet att peka på rätt metod när jag anropar jest.spyOn().
Det är lite klurigt men du kommer att hitta metoderna i din klass på det här sättet:
const spy = jest.spyOn(App.prototype.constructor.options.methods, 'deviceId');
Observera att (även om det kan verka självklart, bara för säkerhets skull) behöver du göra detta innan du omsluter din komponent, alltså så här:
const spy = jest.spyOn(App.prototype.constructor.options.methods, 'deviceId');
wrapper = mount(App, { /* Your options go here */ });
Förresten behöver du inte definiera metoder-egenskapen inuti alternativ.
Svar #2
Definiera din metod under egenskapen methods. Först då kan du få åtkomst till dem från klassen.
export default class App extends Vue {
methods: {
deviceId(){
console.log("do your stuff")
}
}
}
Se här för fler exempel på användningen av methods
