【问题标题】:Cypress spy not being called when VueJS component emits eventVueJS 组件发出事件时未调用 Cypress 间谍
【发布时间】:2023-01-31 17:56:31
【问题描述】:

我正在尝试按照指南here 来测试发出的事件。

鉴于以下 Vue SFC:

<script setup>
</script>

<template>
  <button data-testid="credits" @click="$emit('onCredits')">Click</button>
</template>

以及以下赛普拉斯测试:

import { createTestingPinia } from '@pinia/testing';

import Button from './Button.vue';

describe('<Button />', () => {
  it('renders', () => {
    const pinia = createTestingPinia({
      createSpy: cy.spy(),
    });

    cy.mount(Button, {
      props: {
        onCredits: cy.spy().as('onCreditsSpy'),
      },
      global: {
        plugins: [pinia],
      },
    });

    cy.get('[data-testid=credits]').click();
    cy.get('@onCreditsSpy').should('have.been.called');
  });
});

我的测试失败了

期望 onCreditsSpy 至少被调用一次,但它从未被调用过

把间谍当作道具传递感觉很奇怪,我是不是误会了什么?

【问题讨论】:

    标签: vue.js cypress sinon


    【解决方案1】:

    我用 Using Vue Test Utils 中的最后一个例子解决了这种情况。

    在我的例子中,PagerElement 组件使用属性“pages”来表示要呈现的页面总数,并使用“page”来表示当前页面,此外还有“handleClick”-单击页面后发出的事件:

        cy.mount(PagerElement, {
          props: {
            pages: 5,
            page: 0
          }
        }).get('@vue')
    

    在测试中,我单击第三个链接,然后发出事件:

        cy.get('.pages router-link:nth-of-type(3)').click()
        cy.get('@vue').should(wrapper => {
          expect(wrapper.emitted('handleClick')).to.have.length
          expect(wrapper.emitted('handleClick')[0][0]).to.equal('3')
        })
    

    第一个期望是 handleClick 被发出,第二个期望然后检查发出的参数(在我的例子中,元素的页面被点击)

    为了让 Wrapper-element 返回一个自定义的 mount-command 必须添加而不是 component.ts/component.js 中的默认值:

        Cypress.Commands.add('mount', (...args) => {
          return mount(...args).then(({ wrapper }) => {
            return cy.wrap(wrapper).as('vue')
          })
        })
    

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 2018-12-04
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      相关资源
      最近更新 更多