问题描述
我是 Cypress component testing 的新手,但我能够为我的 Vue 项目轻松设置它。我目前正在研究是否应该用 Cypress 替换 Jest 来测试我们的 Vue 组件,到目前为止我很喜欢它,我仍然缺少一个主要功能:模拟模块。我第一次尝试使用 cy.stub()
,但它根本不起作用,这可能有意义,因为我不是在尝试模拟 Node.js 中的实际模块,而是在 Webpack 中导入的模块。
为了解决这个问题,我尝试使用能够模拟 Webpack 模块的 rewiremock,但在运行测试时出现错误:
我分叉了 Cypress 的示例并在 this commit 中设置了 Rewiremock。老实说,我不确定我做错了什么。
我真的需要找到一种方法来解决它,否则,我们只会停止考虑 Cypress 而只是坚持 Jest。如果使用 Rewiremock 不是方法,我该如何实现?任何帮助将不胜感激。
解决方法
如果您能够调整 Vue 组件以使其更具可测试性,则可以将该函数模拟为组件属性。
Webpack
vue-loader 在处理 HelloWorld.vue
时,会计算 getColorOfFruits()
并设置 data 属性,所以要在这里模拟这个函数,你需要一个 webpack 重写器,比如 rewiremock。
export default {
name: 'HelloWorld',props: {
msg: String
},data() {
return {
colorOfFruits: getColorOfFruits(),// during compile time
};
},...
Vue 创建的钩子
如果您在 colorOfFruits
钩子中初始化 created()
,您可以在导入后挂载之前存根 getColorOfFruits
函数。
HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{ colorOfFruits.apple }}</h2>
<p>
...
</template>
<script lang="ts">
import { getColorOfFruits } from "@/helpers/fruit.js";
export default {
name: "HelloWorld",getColorOfFruits,// add this function to the component for mocking
props: {
msg: String,},data() {
return {
colorOfFruits: {} // initialized empty here
};
},created() {
this.colorOfFruits = this.$options.colorOfFruits; // reference function saved above
}
});
</script>
HelloWorld.spec.js
import { mount } from "@cypress/vue";
import HelloWorld from "./HelloWorld.vue";
it("mocks an apple",() => {
const getMockFruits = () => {
return {
apple: "green",orange: "purple",}
}
HelloWorld.getColorOfFruits = getMockFruits;
mount(HelloWorld,{ // created() hook called as part of mount()
propsData: {
msg: "Hello Cypress!",});
cy.get("h1").contains("Hello Cypress!");
cy.get("h2").contains('green')
});