当VueJS组件发出事件时,没有调用Cypress spy



我试图按照这里的指南来测试一个发出的事件。

给定以下Vue SFC:

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

和以下Cypress test:

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 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命令,而不是在component.ts/component.js中添加默认的mount命令:

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

最新更新