I'm trying test my React
component with Jest
+ Enzyme
, but when my component has SASS
file ( scss
), is occurring SyntaxError
.
This is my SASS file content:
.user-box {
width: 50px;
height: 50px;
}
And I just import that in my component:
import React from 'react';
import './userBox.scss';
class MyComponent extends React.Component {
render() {
const style = {
borderRadius: '99px'
};
return (
<div>Hello World</div>
);
}
}
export default MyComponent;
Following error message of my test:
If I comment the import './userBox.scss';
, test will be okey.
How to can I test React
component with Jest
+ ‵Enzyme` when has style imported
If you have Babel in your stack, you can fix this in the right way using babel-jest
Just do npm i --save-dev babel-jest
and in your jest settings file add:
"moduleNameMapper": {
"^.+\\.(css|less|scss)$": "babel-jest"
}
You have do define a mock for this kind of file by define moduleNameMapper
in your jest settings.
We are using identity-obj-proxy
. So install it with
npm install identity-obj-proxy --save-dev
and add it your jest setting:
"moduleNameMapper": {
"^.+\\.(css|less|scss)$": "identity-obj-proxy"
}
I have been searching for a while for a solution to a similar problem and I kept coming across the solution above.
I didn't seem to work for me at first but I realised that Jest was simply ignoring anything I added to "jest" in package.json. My setup includes a jest.config.js file. I found that if I added "moduleNameMapper" there, it worked. So now my jest.test.config.js looks something like this:
module.exports = {
setupFiles: ["<rootDir>/testSetup.js"],
moduleNameMapper: {
"^.+\\.(css|scss)$": "identity-obj-proxy",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/fileMocks.js"
}
};
The following information wasn't available before, so I made a pull request on facebook/jest and it was merged .
I wanted to stub style imported in modules, something like:
// module.js
import Style from '@/path/to/style.scss';
import App from './App';
So I created a style stub file:
// test/unit/stubs/style.js
module.exports = '.style-stub{color:red;}';
After messing around with the following jest.conf.js
:
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1', // '@' alias
'^.*\\.scss$': '<rootDir>/test/unit/stubs/style.js',
}
I found that the moduleNameMapper
ordering is important. The @
alias rule was resolving before my .scss
rule, so the style file was loaded as a normal module and would crash the test.
The solution is to put specific rules first.
moduleNameMapper: {
'^.*\\.scss$': '<rootDir>/test/unit/stubs/style.js',
'^@/(.*)$': '<rootDir>/src/$1',
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.