在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远程网络资源非常好用。