【问题标题】:Cypress Vue Component Test Runner - testing a button click has emitted an eventCypress Vue 组件测试运行程序 - 测试按钮单击已发出事件
【发布时间】:2022-01-09 16:03:25
【问题描述】:

我无法确定如何对 Vue 组件进行简单测试(使用 Cypress 组件测试运行程序)以查看按钮单击是否导致事件被触发

// MyButton.vue component
    <template>
      <Button
        data-testid="button"
        label="Click Button"
        @click="clickButton()"
      />
    </template>
    <script setup lang="ts">
    import { defineEmits } from "vue";
    const emit = defineEmits(["clickButtonEvent"]);
    
    function clickButton() {
      emit("clickButtonEvent");
    }
    </script>
// MyButton.spec.ts
    it.only("should emit an even when clicked", () => {
      const clickButtonSpy = cy.spy().as("clickButtonEvent");
    
      mount(FulfilButton, {
        global: {
          components: {
            Button,
          },
        },
      })
      .get('[data-testid="button"]')
      .click();
    
      cy.get("@clickButtonEvent").should("have.been.called");
    });

这不起作用 - 在我看到的控制台中

mount
get
-click

然后这个:

expect clickButtonEvent to have been called at least once, but it was never called

所以我想我没有正确连接这个cy.spy - 大概是因为我没有将它作为安装的一部分?我需要做什么?按钮本身是 PrimeVue 按钮组件,但我很确定这不会阻止我进行此测试?

【问题讨论】:

    标签: vue.js unit-testing cypress cypress-component-test-runner


    【解决方案1】:

    好吧,你根本没有勾搭间谍。

    Cypress mount 命令与vue-test-utils mount 具有相同的界面(它在后台使用vue-test-utils

    vue-test-utils v1(适用于 Vue 2)中,您可以使用 listeners 挂载选项来附加间谍,如 this answer 中所示

    但是由于您使用的是 Vue 3,而 vue-test-utils v2 又是 listeners 挂载选项 was removed,可能是使用推荐的包装器 API 的最佳选择 - emitted

    这个例子取自recent talk of Jessica Sachs(赛普拉斯团队成员)(repo),她做了这样的事情:

    mount(FulfilButton, {
      global: {
        components: {
          Button,
        },
      },
    })
    .get('[data-testid="button"]')
    .click()
    .vue()
    .then((wrapper) => {
      expect(wrapper.emitted('clickButtonEvent')).to.have.length(1)
    })
    

    注意 vue() 不是内置的 Cypress 命令。在这个 demo/repo 中,它是由 Jessica 在 support file

    中添加的
    // ./cypress/support/index.js
    
    Cypress.Commands.add('vue', () => {
      return cy.wrap(Cypress.vueWrapper)
    })
    

    您可以在不引入任何帮助程序的情况下执行非常相似的操作 (example)

    it('emits "increment" event on click', () => {
        cy.get('button')
        .click()
        .click()
        .then(() => {
          cy.wrap(Cypress.vueWrapper.emitted()).should('have.property', 'increment')
        })
      })
    

    【讨论】:

    • 谢谢 - 实际上我看了同样的演讲,昨天我联系了杰西卡关于这个 vue() 命令,因为这对我不起作用(我得到“属性 vue 在 Chainable>”- 她说 Vue 命令是“默认情况下未安装”,我不完全确定这意味着什么 - 你呢?这正是我想做这个测试的方式,但没有 Vue 命令在那里我不能
    • 抱歉 - 她说的不是“默认添加”
    • 谢谢! cy.wrap(Cypress.vueWrapper.emitted()).should('have.property' 似乎有效
    猜你喜欢
    • 2023-01-23
    • 2020-10-10
    • 1970-01-01
    • 2020-04-26
    • 2022-09-30
    • 2021-05-23
    • 2022-08-23
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多