【问题标题】:Weird behavior of Cypress spy() functionCypress spy() 函数的奇怪行为
【发布时间】:2021-05-13 16:42:40
【问题描述】:

我在 Cypress 测试 wen 监视 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(我在测试中设置的别名)。

非常感谢。

【问题讨论】:

    标签: vue.js vuejs2 cypress


    【解决方案1】:

    我发现 Cypress spy() 将方法及其上下文包装起来。将方法传递给另一个组件,会改变它的上下文,所以它不会被算作一次调用。为了能够在当前组件中记录它的调用,我还必须传递当前上下文。

    <child-component :propMethod="parentMethod.apply(this)">
    

    【讨论】:

    • 这是完全正确的。做得好。 JS 中旧的经典上下文“this”的一个很好的例子。
    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 2011-06-14
    • 2020-01-31
    • 2014-05-24
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多