用jest.mock传递范围外的变量 [英] Passing out-of-scope variable with jest.mock

查看:142
本文介绍了用jest.mock传递范围外的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用来模拟react-native的模拟对象:

I have a mock object that I am using to mock react-native:

const MyMock = {
    MockA: {
        methodA: jest.genMockFn()
    },
    MockB: {
        ObjectB: {
            methodA: jest.genMockFn(),
            methodB: jest.genMockFn(),
        }
    }
};


jest.mock('react-native', () => {
    return MyMock;
});

我在jest.mock之外声明了该对象,因为稍后在测试中也需要它:

I am declaring the object outside of jest.mock because I also need it later on in my tests:

describe('MyClass', () => {
     beforeEach(() => {
         MyMock.MockB.ObjectB.methodA.mockClear();
         MyMock.MockB.ObjectB.methodB.mockClear();
     });
     //some other code

我收到此错误:

jest.mock()的模块工厂不允许引用任何范围外的变量.

The module factory of jest.mock() is not allowed to reference any out-of-scope variables.

问题是我在jest.mock之外声明了MyMock.但据我所知,我别无选择.

The problem is that I declare MyMock outside of jest.mock. But I have no choice as far as I can see.

那么如何在将MyMock保留在jest.mock之外的同时使代码正常工作?

So how can I make the code work while keeping MyMock outside of jest.mock?

推荐答案

我没有完全阅读错误消息.在最后一行(略微模糊)是:

I hadn't read the error message fully. On the last line(slightly obscured) there is this:

注意:这是防止未初始化的模拟变量的预防措施.如果确保懒惰地需要该模拟,则允许以mock为前缀的变量名.

Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with mock are permitted.

因此,当我将MyMock更改为例如mockMyMock时,它就起作用了.

So when I changed MyMock to for instance mockMyMock, it worked.

这篇关于用jest.mock传递范围外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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