【问题标题】:Monkey-patching jest object for all test files所有测试文件的猴子补丁玩笑对象
【发布时间】:2019-03-08 11:52:55
【问题描述】:

如何为所有测试文件同时对全局 jest 对象中的某些方法进行猴子修补?我不想在我的测试文件中添加任何额外的代码,它必须在设置中的某个地方完成,这可能是一个丑陋的 hack。

我尝试在自定义环境 setupFiles 和 setupFilesAfterEnv 中执行此操作,但看起来它们都获得了 jest 对象的不同实例,并且我的更改在测试文件中不可见。

免责声明:我知道这是一件坏事,但我只需要它来进行一次性基准测试,它是完成工作的最简单的解决方案。

【问题讨论】:

标签: javascript node.js testing jestjs monkeypatching


【解决方案1】:

我得到了这个工作!没错,Jest 确实为每个测试用例重新构造了全局 jest 对象,但是您可以覆盖它用来执行此操作的函数。在jest.config.js 中,将globalSetup 设置为<rootDir>/jest-global-setup.js。然后,在jest-global-setup.js 中添加:

const jestRuntime = require('jest-runtime');

const { _createJestObjectFor } = jestRuntime.prototype;

jestRuntime.prototype._createJestObjectFor = function(...args) {
    // Call the original function to create a normal jest object.
    const jestObject = _createJestObjectFor.apply(this, args);

    // Apply your changes.
    jestObject.isMonkeyPatched = true;
    
    // Return the patched object.
    return jestObject;
}

// Jest expects to find a function of some sort as well, 
// but we don't need it for this example.
module.exports = function() { /* do nothing */ }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 2012-09-16
    • 2012-12-18
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    相关资源
    最近更新 更多