我在Cypress测试中发现了一个奇怪的问题,即监视vue组件方法。我设置了一个用于演示的最小示例组件。
<template>
<button @click="testMethod()”>Button</button>
</template>
<script>
export default {
name: "ExampleComponent",
methods: {
testMethod () {
console.log(this.testMethod) // for debugging purposes
console.log("Button clicked")
}
}
}
</script>
这就是测试:
import { mount } from "@cypress/vue"
import exampleComponent from "../example"
it("should spy on testMethod", () => {
mount(exampleComponent).then(() => {
cy.spy(Cypress.vueWrapper.vm, "testMethod").as("testMethodSpy")
cy.get("button").click()
cy.get("@testMethodSpy").should("be.calledOnce")
})
})
当我运行这个测试时,它通过了。在控制台中我得到:
ƒ testMethod
Button clicked
但是,如果我将"testMethod"指针传递给@click指令,如下所示:
<template>
<button @click="testMethod”>Button</button>
</template>
则测试失败。它抱怨该方法从未被调用,即使在控制台中我得到了。
ƒ testMethodSpy
Button clicked
我不明白为什么当方法被传递给事件指令时,即使调用了它,柏树也不能注册调用。此外,为什么方法名称在失败时更改为testMethodSpy
(我在测试中设置的别名(。
非常感谢。
我发现Cypress spy((正在包装方法及其上下文。将该方法传递给另一个组件将更改其上下文,因此不会将其算作调用。为了能够在当前组件中记录它的调用,我还必须传递当前上下文。
<child-component :propMethod="parentMethod.apply(this)">