I wished to try snapshot testing a larger component, but my component fails because of the formik component inside (tested by removing it)
import {
RadiusInputField,
createValidators,
requiredValidator,
VALIDATE_REQUIRED_TYPES
} from '../../../core/components/formik'
This formik component is used in a styled component:
const TextBoxContainer = styled(RadiusInputField)`
and I get the following error:
/Users/ravelyn/dev/kobiton/portal/node_modules/flexboxgrid/dist/flexboxgrid.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.container-fluid,
^
SyntaxError: Unexpected token '.'
I have tested that I can import a css module separately in another test without any problem.
My jest config is configured as so:
const config = {
"automock": false,
"rootDir": "src",
"modulePaths": ["<rootDir>"],
"moduleFileExtensions": ['js', 'jsx'],
"moduleDirectories": ["node_modules"],
"moduleNameMapper": {
"^src(.*)$": "<rootDir>",
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
'. .(css|less)$': 'identity-obj-proxy'
},
"transform": {
'\\.[jt]sx?$': 'babel-jest'
}
};
module.exports = config;
and my test is like so:
import React from "react";
import renderer from 'react-test-renderer';
import theme from '../../../../main/theme';
import Component from "../component-under-test";
import {ThemeProvider} from 'styled-components'
it("should render a gesture dialog text box", () => {
const tree = renderer
.create(
<ThemeProvider theme={theme}>
<Component />
</ThemeProvider>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
CodePudding user response:
The issue is likely caused by the fact that you are importing a CSS module inside a Jest test, which is not supported by Jest. Jest does not support importing CSS modules directly, and will throw an error when it encounters a .css or .less import in your code.
To fix this issue, you will need to mock the CSS module using the jest.mock function. This will allow Jest to replace the CSS module with a mock implementation, which will prevent the error from occurring.
Here's an example of how you could do this:
- In the test file, use the jest.mock function to mock the CSS module:
jest.mock('../../../core/components/formik', () => ({
RadiusInputField: () => <div />,
createValidators: () => {},
requiredValidator: () => {},
VALIDATE_REQUIRED_TYPES: {},
}));
- Import the mocked CSS module in the test file:
import '../../../core/components/formik';
After making these changes, the test should be able to import the CSS module without throwing an error, and the test should pass. Let me know if you have any further questions!