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
To add SCSS styles to a React project, we can install the sass package if the React project is created with create-react-app. Then we import a SCSS file by writing: import '../scss/styles.
The Sass @import directive extends the CSS @import rule so that it works with . scss and . sass files. It imports the file referenced and any variables or mixins that are defined in the imported file so they can be used in the main file.
It is now possible to import css files directly into your sass file. The following PR in github solves the issue. The syntax is the same as now - @import "your/path/to/the/file" , without an extension after the file name. This will import your file directly.
The SASS @import function helps us to import multiple SASS or CSS stylesheets together such that they can be used together. Importing a SASS file using the @import rule allows access to mixins, variables, and functions to the other file in which the other file is imported. Syntax: @import path_of_file.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With