8

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>
  )
}
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • Possible duplicate of [SyntaxError with Jest and React and importing CSS files](https://stackoverflow.com/questions/39418555/syntaxerror-with-jest-and-react-and-importing-css-files) – Andrea Carraro Feb 17 '18 at 16:07

1 Answers1

3

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.

fyasir
  • 2,924
  • 2
  • 23
  • 36