模拟特定测试组的模块中的常量属性 [英] Mock a constant property from a module for a specific test group
本文介绍了模拟特定测试组的模块中的常量属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有MyComponent.tsx
,它使用constants.ts
模块来根据IS_IOS
常量执行某些操作:
import React from 'react';
import { Text, View } from 'react-native';
import { platform } from '../../constants';
const { IS_IOS } = platform;
interface Props {}
export const MyComponent = (props: Props) => {
return (
<View>
<Text>Alpha Beta { String(IS_IOS) }</Text>
</View>
);
};
我尝试在每个测试中以不同的方式模拟constants.ts
。我尝试了here和here的所有方法,但仍然没有结果。该模块根本没有被嘲笑。以下是我的测试文件和组件文件:
MyComponent.test.tsx
:
// @ts-nocheck
import React from 'react';
import { cleanup, render } from '@testing-library/react-native';
import { MyComponent } from '../../../src/MyComponent';
describe('MyComponent', () => {
afterEach(() => {
jest.resetModules();
jest.clearAllMocks();
cleanup();
});
it('one', () => {
jest.mock('../../../src/constants', () => ({
platform: { IS_IOS: false }
}));
const { debug } = render(<MyComponent/>);
debug();
});
it('two', () => {
jest.mock('../../../src/constants', () => ({
platform: { IS_IOS: true }
}));
const { debug } = render(<MyComponent/>);
debug();
});
});
这是我进入控制台的结果:
console.log
<View>
<Text>
Alpha Beta
true
</Text>
</View>
at debugDeep (node_modules/@testing-library/react-native/build/helpers/debugDeep.js:19:13)
console.log
<View>
<Text>
Alpha Beta
true
</Text>
</View>
at debugDeep (node_modules/@testing-library/react-native/build/helpers/debugDeep.js:19:13)
现在,如果我将jest.mock
放在文件的开头,它就可以工作,但问题是它用相同的值模拟IS_IOS
(即IS_IOS = false
):
// @ts-nocheck
import React from 'react';
import { cleanup, render } from '@testing-library/react-native';
import { MyComponent } from '../../../src/MyComponent';
jest.mock('../../../src/constants', () => ({
platform: { IS_IOS: false }
}));
describe('MyComponent', () => {
afterEach(() => {
jest.resetModules();
jest.clearAllMocks();
cleanup();
});
it('one', () => {
const { debug } = render(<MyComponent/>);
debug();
});
it('two', () => {
const { debug } = render(<MyComponent/>);
debug();
});
});
如我所说,这两种情况下都是嘲笑:
console.log
<View>
<Text>
Alpha Beta
false
</Text>
</View>
at debugDeep (node_modules/@testing-library/react-native/build/helpers/debugDeep.js:19:13)
console.log
<View>
<Text>
Alpha Beta
false
</Text>
</View>
at debugDeep (node_modules/@testing-library/react-native/build/helpers/debugDeep.js:19:13)
我已尝试jest.doMock
,尝试添加__esModule
-均不起作用。如何在每次测试中以不同方式模拟模块?
提前感谢您抽出时间!
推荐答案
jest.resetModules
不能影响已导入的模块。它应该与测试的本地require
组合在一起,以便特定于测试的jest.mock
影响它。
ES模块应使用MAGIC__esModule
属性进行模拟,以便它们不会被处理为CommonJS模块:
jest.mock('../../../src/constants', () => ({
__esModule: true,
platform: { IS_IOS: false }
}));
const { MyComponent } = require('../../../src/MyComponent');
这篇关于模拟特定测试组的模块中的常量属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文