在 Jest 中有什么方法可以模拟全局对象,例如 navigator
或 Image
*?我几乎放弃了这一点,并将其留给了一系列可模拟的实用方法。例如:
// Utils.js
export isOnline() {
return navigator.onLine;
}
测试这个小函数很简单,但很麻烦,而且根本不确定。我可以完成 75% 的路程,但这是我所能达到的极限:
// Utils.test.js
it('knows if it is online', () => {
const { isOnline } = require('path/to/Utils');
expect(() => isOnline()).not.toThrow();
expect(typeof isOnline()).toBe('boolean');
});
另一方面,如果我接受这种间接访问,我现在可以通过这些实用程序访问 navigator
:
// Foo.js
import { isOnline } from './Utils';
export default class Foo {
doSomethingOnline() {
if (!isOnline()) throw new Error('Not online');
/* More implementation */
}
}
...并像这样进行确定性测试...
// Foo.test.js
it('throws when offline', () => {
const Utils = require('../services/Utils');
Utils.isOnline = jest.fn(() => isOnline);
const Foo = require('../path/to/Foo').default;
let foo = new Foo();
// User is offline -- should fail
let isOnline = false;
expect(() => foo.doSomethingOnline()).toThrow();
// User is online -- should be okay
isOnline = true;
expect(() => foo.doSomethingOnline()).not.toThrow();
});
在我使用过的所有测试框架中,Jest 感觉是最完整的解决方案,但每当我编写笨拙的代码只是为了使其可测试时,我觉得我的测试工具让我失望。
这是唯一的解决方案还是我需要添加 Rewire?
*别傻笑。 Image
非常适合 ping 远程网络资源。
最佳答案
由于每个测试套件 都运行自己的环境,因此您可以通过覆盖它们来模拟全局变量。所有全局变量都可以通过 global
命名空间访问:
global.navigator = {
onLine: true
}
覆盖仅对您当前的测试有效,不会影响其他测试。这也是处理 Math.random
或 Date.now
的好方法。
请注意,通过 jsdom 中的一些更改您可能必须像这样模拟全局变量:
Object.defineProperty(globalObject, key, { value, writable: true });
关于javascript - 在 Jest 中模拟全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40449434/