You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中测试返回值为void的简单方法?

问题原因
  • 测试用例内重新声明了同名局部变量stopped,和源码中的模块级/全局变量完全独立,校验该局部变量无法得到正确结果。
  • 源码中未对外暴露stopped变量,测试环境默认无法直接访问该模块私有变量。
  • 额外注意:你的源码存在语法错误,export const = stopDoingStuff = () => { 多写了一个等号,需修正为export const stopDoingStuff = () => {。
解决方法

方案1:源码侧暴露测试用访问入口(推荐)

修改源码,新增仅用于测试的变量读取方法,生产环境可通过构建树摇移除相关代码:

let stopped = false; // 模块级变量

export const stopDoingStuff = () => {
  stopped = true;
}

// 测试用导出
export const _test_getStoppedStatus = () => stopped;

调整后的测试代码:

import { stopDoingStuff, _test_getStoppedStatus } from '你的源码模块路径';

it('should set stopped to true', () => {
  stopDoingStuff();
  expect(_test_getStoppedStatus()).to.equal(true);
});

方案2:若stopped为window全局变量

如果你的stopped是直接挂载在window对象上的真全局变量,无需修改源码,直接在测试中访问window对象即可:

import { stopDoingStuff } from '你的源码模块路径';

it('should set stopped to true', () => {
  stopDoingStuff();
  expect(window.stopped).to.equal(true);
});

内容的提问来源于stack exchange,提问作者Codehan25

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:36:06