如何使用Cypress模拟代码中的单个函数使其始终返回true
解决Cypress中模拟setReceptionMode始终返回true的问题
以下是几种可行的实现方式,根据你的项目结构选择:
方式一:直接Stub ES模块导出
如果你的测试文件能直接导入目标模块,可通过cy.stub替换函数返回值:
// 导入目标模块,路径根据你的项目结构调整 import * as receptionUtils from '../src/utils/file.js' describe('Reception Mode Test', () => { beforeEach(() => { // 替换setReceptionMode函数,使其始终返回true cy.stub(receptionUtils, 'setReceptionMode').returns(true) }) it('should trigger reception mode behavior', () => { cy.visit('/target-page') // 这里添加断言,验证函数返回true后的预期行为 }) })
注意:如果模块被打包工具(如Webpack)缓存或树摇,可能需要在Cypress配置中启用experimentalModuleRewriting(Cypress 10+支持),在cypress.config.js中添加:
module.exports = { e2e: { experimentalModuleRewriting: true } }
方式二:通过Window对象Stub函数
如果模块未被直接导入到测试文件,可先将函数挂载到window对象,再进行Stub:
- 在
file.js中添加测试环境下的挂载逻辑:
export const setReceptionMode = () => { if (window.location.host === process.env.VUE_APP_RECEPTION_HOST) { return true; } return false; }; // 仅在测试/开发环境挂载到window if (process.env.NODE_ENV !== 'production') { window.setReceptionMode = setReceptionMode; }
- 在Cypress测试中提前Stub:
describe('Reception Mode Test', () => { beforeEach(() => { cy.visit('/target-page', { onBeforeLoad(win) { // 在页面加载前Stub函数 cy.stub(win, 'setReceptionMode').returns(true) } }) }) it('should behave correctly in reception mode', () => { // 执行测试并断言 }) })
方式三:修改环境变量实现
如果不想Stub函数,可直接在Cypress中设置对应环境变量,让函数自然返回true:
在cypress.config.js中配置环境变量:
const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { env: { // 将测试环境的host设置为匹配值 VUE_APP_RECEPTION_HOST: Cypress.config('baseUrl').replace(/^https?:\/\//, '') } } })
这样window.location.host会和环境变量匹配,函数自动返回true。
内容的提问来源于stack exchange,提问作者Alex López
相关产品推荐
相关产品推荐

