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

如何在Jest测试中Mock Player类makeMove方法内的paint函数?

解决Jest测试Player类makeMove方法时的document未定义问题

测试Player类的makeMove方法时,触发ReferenceError: document is not defined错误,原因是makeMove里调用的paint函数操作DOM,而Jest运行在Node.js环境不支持浏览器DOM API。尝试Mock paint函数但未成功,目标是测试makeMove时不执行实际的paint逻辑。

方法1:Mock单个Player实例的paint方法

创建Player实例后,直接将其paint方法替换为空函数或Jest mock函数,调用makeMove时就不会执行原paint的DOM操作。

修改后的测试代码:

import { Player } from "./player.js"

describe("Test the class Player", ()=>{
    test("Check the method makeMove()", ()=>{
        const player = new Player();
        // Mock实例的paint方法,替换为空函数
        player.paint = jest.fn();
        const move = player.makeMove();
        // 修正原测试中的错误:exportAllDeclaration → expect
        expect(move).toBeLessThan(101);
        // 可选:验证paint方法是否被调用,参数是否正确
        expect(player.paint).toHaveBeenCalledWith(move);
    });
});

方法2:Mock Player类原型的paint方法

如果需要对所有Player实例生效,用jest.spyOnMock类的原型方法,测试后可恢复原方法:

import { Player } from "./player.js"

describe("Test the class Player", ()=>{
    let paintSpy;

    beforeEach(() => {
        // Mock Player原型的paint方法
        paintSpy = jest.spyOn(Player.prototype, 'paint').mockImplementation(() => {});
    });

    afterEach(() => {
        // 测试结束后恢复原方法
        paintSpy.mockRestore();
    });

    test("Check the method makeMove()", ()=>{
        const player = new Player();
        const move = player.makeMove();
        expect(move).toBeLessThan(101);
        expect(paintSpy).toHaveBeenCalledWith(move);
    });
});

额外注意事项

  1. 原测试代码中的exportAllDeclaration是错误写法,需改为expect,否则测试会直接报错。
  2. makeMove方法中还用到了Audio和Gameboard,这些在Jest环境中也可能触发错误:
    • 针对Audio,可在测试文件开头Mock全局Audio对象:
      global.Audio = jest.fn(() => ({ play: jest.fn() }));
      
    • 针对Gameboard,需确保正确导入,若其方法依赖DOM或浏览器API,也要对应Mock相关逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:42:44