I have MyComponent.tsx
that uses constants.ts
module in order to do something based on the IS_IOS
constant:
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>
);
};
I am trying to mock constants.ts
differently in each test. I have tried all methods from here and here, but still no results. The module is not mocked at all. Here are my test file, and component file:
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();
});
});
This is the result that I get into the console:
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)
Now, it works if I put jest.mock
at the beginning of the file, but the problem is that it mocks IS_IOS
with same value (i.e. 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();
});
});
As I said, mocks in both cases:
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)
I have tried jest.doMock
, tried adding __esModule
- none of it works. How do I mock module differently in each test?
Thanks in advance for your time!
question from:
https://stackoverflow.com/questions/65843017/mock-a-constant-property-from-a-module-for-a-specific-test-group