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

如何在测试文件中复用变量并仅对特定测试临时修改其值?

解决测试中复用变量且修改不影响其他测试的问题

你遇到的核心问题是引用类型的共享修改:因为props是一个对象,直接修改它的属性会改变这个对象本身,后续测试再引用它时,拿到的就是已经被修改过的版本了。要让每个测试都能使用干净的初始对象,有两种常用的解决思路:

方法1:用beforeEach在每个测试前重置变量

把变量的初始化放到beforeEach钩子里面,这样每个测试执行前都会重新创建一个全新的初始对象,完全隔离各个测试的修改:

let props;

describe('example()', () => {
  // 每个测试运行前都重置props为初始状态
  beforeEach(() => {
    props = { id: 'M1234567890', update: jest.fn() };
  });

  it('should not call update if id is missing', () => {
    // 这里修改的是当前测试专属的props对象
    props.id = undefined;
    const component = shallow(<Component {...props} />);
    
    // 你的测试逻辑...
  });

  it('should call update when triggered', () => {
    // 这里的props是全新的初始值,不受上一个测试影响
    const component = shallow(<Component {...props} />);
    
    // 你的测试逻辑...
    expect(props.update).toHaveBeenCalled();
  });
});

方法2:创建对象副本进行修改

如果不想用钩子,也可以在需要修改的测试里,基于初始对象创建一个副本,修改副本的属性——这样原对象始终保持初始状态,后续测试可以直接复用:

// 定义基础的初始对象,永远不直接修改它
const baseProps = { id: 'M1234567890', update: jest.fn() };

describe('example()', () => {
  it('should not call update if id is missing', () => {
    // 用扩展运算符创建副本,覆盖需要修改的属性
    const props = { ...baseProps, id: undefined };
    const component = shallow(<Component {...props} />);
    
    // 你的测试逻辑...
  });

  it('should call update when triggered', () => {
    // 直接使用原基础对象,或者也可以创建副本保证绝对干净
    const component = shallow(<Component {...baseProps} />);
    
    // 你的测试逻辑...
    expect(baseProps.update).toHaveBeenCalled();
  });
});

如果你的对象嵌套比较深,扩展运算符可能无法完全深拷贝,这时候可以用structuredClone(baseProps)来创建深副本,确保嵌套属性也不会被共享修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:33:19