I need to mock an imported CSS file in my jest/enzyme test:
Header.test.js
import React from 'react'
import { shallow } from 'enzyme'
import { Header } from './Header'
jest.mock('semantic-ui-css/semantic.min.css') // <-- no effect...
it('should render page title', () => {
const wrapper = shallow(<Header title='Test' />)
expect(wrapper.find('title').text()).toEqual('Test')
})
I do get the error for the import 'semantic-ui-css/semantic.min.css'
line:
Test suite failed to run
/Users/node_modules/semantic-ui-css/semantic.min.css:11
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic&subset=latin);/*!
^
SyntaxError: Invalid or unexpected token
I don't need import the css file for the test. So I would like to mock that import out for the test. How can I do that?
I tried to do jest.mock('semantic-ui-css/semantic.min.css')
but that doesn't work.
This is how the Header.js looks like:
Header.js
import Head from 'next/head'
import 'semantic-ui-css/semantic.min.css'
export const Header = props => {
return (
<Head>
<meta http-equiv='content-type' content='text/html;charset=UTF-8' />
<meta charset='utf-8' />
<title>{props.title}</title>
<link rel='icon' href='/static/favicon.ico' />
<link rel='stylesheet' href='/_next/static/style.css' />
</Head>
)
}
You can create your own mock in jest to prevent processing of css files. // __mocks__/styleMock. js module. exports = {};
moduleNameMapper [Object] (Default: null) This configuration holds the key to file mocking. By using this configuration all the external asset files like images and style files will be mocked, as these files are not intended to be tested. So, while running test cases, only the the mock files are imported.
Often you won't need webpack to run your tests. Tools such as Jest, Cypress, Puppeteer, and Playwright cover the problem well. Often there are ways to adapt to webpack specific syntax in case you are using webpack features within your code.
A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. CSS Modules let you write styles in CSS files but consume them as JavaScript objects for additional processing and safety.
Use ignore-styles package in your jest config.
npm install --save-dev ignore-styles
In your jest.config.js file include these lines
import register from 'ignore-styles';
register(['.css', '.sass', '.scss']);
jest-css-modules is the another package you can try.
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