我在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")
})
})
当我运行这个测试时,它通过了ok。在控制台中,我得到:
ƒ testMethod
Button clicked
但如果我将‘testMethod’指针传递给@click指令,如下所示:
<template>
<button @click="testMethod”>Button</button>
</template>
那么测试将失败。它抱怨这个方法从来没有被调用过,即使在控制台中我得到了。
ƒ testMethodSpy
Button clicked
我不明白为什么当方法被传递给事件指令时,cypress不能注册调用,即使它被调用了。另外,为什么方法名在失败时更改为testMethodSpy
(我在测试中设置的别名)。
在此之前,非常感谢您。
发布于 2021-05-14 05:28:49
我发现Cypress spy()封装了方法及其上下文。将该方法传递给另一个组件将更改其上下文,因此不会将其计入调用。为了能够在当前组件中记录它的调用,我还必须传递当前上下文。
<child-component :propMethod="parentMethod.apply(this)">
https://stackoverflow.com/questions/67522995
复制相似问题