在Jest中模拟全局变量 [英] Mocking globals in Jest

查看:2605
本文介绍了在Jest中模拟全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jest有没有办法模拟全局对象,例如 navigator Image *?我已经放弃了这一点,并将其放在一系列可笑的实用方法上。例如:

Is there any way in Jest to mock global objects, such as navigator, or Image*? I've pretty much given up on this, and left it up to a series of mockable utility methods. For example:

// Utils.js
export isOnline() {
    return navigator.onLine;
}

测试这个微小的功能很简单,但绝对而不是确定性。我可以得到75%的方式,但是这是我能走的最远的一步:

Testing this tiny function is simple, but crufty and not deterministic at all. I can get 75% of the way there, but this is about as far as I can go:

// 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 通过这些实用程序:

On the other hand, if I am okay with this indirection, I can now access navigator via these utilities:

// Foo.js
import { isOnline } from './Utils';

export default class Foo {
    doSomethingOnline() {
        if (!isOnline()) throw new Error('Not online');

        /* More implementation */            
    }
}

...并确定性地测试这样...

...and deterministically test like this...

// 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感觉就像最完整的解决方案,但是任何时间我写尴尬的代码只是为了使其可测试,我觉得我的测试工具让我失望。

Out of all the testing frameworks I've used, Jest feels like the most complete solution, but any time I write awkward code just to make it testable, I feel like my testing tools are letting me down.

这是唯一的解决方案,还是需要添加Rewire?

Is this the only solution or do I need to add Rewire?

*不要傻笑。 图像对于ping远程网络资源是非常好的。

*Don't smirk. Image is fantastic for pinging a remote network resource.

推荐答案

测试运行自己的环境,你可以通过覆盖它们来模拟全局变量。所有全局变量都可以通过全局名称空间访问。

As every test run its own environment you can mock globals by just overwrite them. All global vars can be accessed by the global name space.

global.navigator = {
  onLine: true
}

覆盖只有效果在你当前的测试中,不会影响他人。这也是处理 Math.random Date.now

The overwrite has only effects in your current test and will not effect others. This also a good way to handle Math.random or Date.now

这篇关于在Jest中模拟全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆