Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a css import for jest/enzyme test?

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>
  )
}
like image 978
user3142695 Avatar asked Feb 17 '18 13:02

user3142695


People also ask

How do I make jest ignore CSS?

You can create your own mock in jest to prevent processing of css files. // __mocks__/styleMock. js module. exports = {};

What does moduleNameMapper do in jest?

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.

Does jest need webpack?

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.

What is CSS modules?

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.


1 Answers

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.

like image 104
fyasir Avatar answered Oct 28 '22 06:10

fyasir