简体   繁体   中英

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>
  )
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM