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 感觉是最完整的解决方案,但是每当我编写笨拙的代码只是为了使其可测试时,我觉得我的测试工具让我失望。
这是唯一的解决方案还是我需要添加重新布线?
*别笑。Image非常适合 ping 远程网络资源。