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

查看:31
本文介绍了使用 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天全站免登陆