cypress 组件测试未捕获从我的 Vue3 组件发出的更新事件

sam*_*tha 3 cypress cypress-component-test-runner cypress-intercept

我是组件测试和在赛普拉斯中使用间谍的新手,所以这可能是一个愚蠢的问题。

我有一个非常简单的组件,我正在测试它,当您在组件中进行选择时,选择会通过 modelValue 属性发送回父级。

我的组件在我的应用程序中工作(v-model 更新为选择的正确值就好),但我似乎无法在测试中捕获和验证它。

在我的组件内部,这是我执行发射的方式:

handleSelectionChange() {
  console.log("emitting update:modelValue= ", this.selectedOption);
  this.$emit('update:modelValue', this.selectedOption);
}, 
Run Code Online (Sandbox Code Playgroud)

控制台显示测试运行时值的变化,所以我认为这部分没问题。同样,当我在应用程序中使用该组件时,v-model 正在更新,因此我希望这不是问题。

我的Cypress 组件测试如下所示:

it.only('should emit an event when the value is changed', () => {
const mockData = ["one", "two", "three"];

cy.intercept('GET', '/v1/product', {
  statusCode: 200,
  body: mockData,
}).as('getProductData');

cy.mount(ProductPicker, {
  props: { modelValue: null },
  on: {
    'update:modelValue': cy.spy().as('updateModelValueSpy'),
  },
}).then(() => {
  cy.get('select').select('two');

  // Wait added as part of trouble shooting, hopefully not needed
  cy.wait(500); 

  // Ensure the spy has captured the emitted event
  cy.get('@updateModelValueSpy').should('have.been.called');
});
Run Code Online (Sandbox Code Playgroud)

});

当测试运行时,我看到值“two”打印到控制台,因此测试调用了我的函数,该函数似乎正在发出“update:modelValue”事件...

但测试失败并显示以下消息: assertexpected updateModelValueSpy 已被调用至少一次,但从未被调用

几天来我花了几个小时来处理这个问题。有人有什么我可以尝试的吗?

我的目的只是验证在做出选择时我安装的控件的 v 模型是否已更新。

Tes*_*ick 5

我不知道如何将间谍附加到事件,但这个问题How to test if a component attempts emits an event in Vue? 显示您可以使用的模式。

如果我使用基本的 HelloWorld Vue 应用程序并添加一个具有类似处理程序的按钮

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="handleSelectionChange">Greet</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }, 
  methods: {
    handleSelectionChange() {
      console.log("emitting update:modelValue= ", 'abc');
      this.$emit('update:modelValue', 'abc');
    },
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

this.$emit可以通过属性访问该wrapper.emitted()调用(其中this=== wrapper

cy.mount(HelloWorld)
  .then(({ wrapper, component }) => {

    cy.get('button').click()

    cy.then(() => {
      expect(wrapper.emitted()['update:modelValue'][0]).to.deep.eq(['abc'])
    })
  })
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述