我有使用constants.ts
模块的MyComponent.tsx
,以便根据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
。我已经从这里到这里尝试了所有的方法,但仍然没有结果。模块根本没有被模拟。下面是我的测试文件和组件文件:
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();
});
});
正如我所说,在这两种情况下都是mock:
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
不能影响已经导入的模块。为了让特定于测试的jest.mock
影响它,它应该与本地的require
结合在一起。
ES模块应该使用magic__esModule
属性来模拟,以便它们不会被当作CommonJS模块处理:
jest.mock('../../../src/constants', () => ({
__esModule: true,
platform: { IS_IOS: false }
}));
const { MyComponent } = require('../../../src/MyComponent');