使用Jest和React模拟非默认功能 [英] Mock a non-default function using Jest and React

查看:55
本文介绍了使用Jest和React模拟非默认功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在测试文件中,我需要在模拟某些子组件的同时渲染组件.文件结构看起来像这样松散.

In a test file I need to render a component while mocking out some of its sub components. The file structure would look loosely something like this.

文件1

import {A, B} from 'a-module';

export function MyComponent() {
    return (
        <div>
            <A /> // I need to mock
            <B /> // these components out
        </div>
    );
}

文件2

import {MyComponent} from 'File 1';

/*
 * In this file I would like to render MyComponent but
 * have components A and B be replaced by mocks
 */

我尝试做jest.mock('a-module', () => 'Blah');,但这没有成功模拟组件.但是,在文件1中使用默认导入时,此方法有效.

I have tried doing jest.mock('a-module', () => 'Blah'); but this is not successfully mocking the components. This works however when using default imports in File 1.

在文件2中呈现MyComponent时,提供任何模拟组件AB的帮助,将是我们的最爱!

Any help in mocking out components A and B when rendering MyComponent in file 2 would be most appreciated!

推荐答案

您可以模拟非默认值,例如:

jest.mock('a-module', () => ({
  __esModule: true,
  default: () => 'Blah',
  A: () => 'Blah',
  B: () => 'Blah'
}));

https://remarkablemark.org/blog /2018/06/28/jest-mock-default-named-export/

或使用__mocks __

或者,您可以在__mocks__文件夹下的原始模块旁边创建一个与模块同名的文件:

as an alternative you could create a file under __mocks__ folder next to the original module with the same name as the module:

a_module_folder > 
    a-module.js
    __mocks__ >
        a-module.js

并且该模拟应该只导出模拟的版本:

and that mock should just export the mocked versions:

export const A = () => 'Blah';
export const B = () => 'Blah';

然后像这样模拟:

jest.mock('a-module');

jest.mock('a-module');

对于node_modules,只需将__mocks__文件夹放在与node_modules相同的级别上

for node_modules just put __mocks__folder on the same level as node_modules

https://jestjs.io/docs/en/manual-mocks

这篇关于使用Jest和React模拟非默认功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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