Ehvince
Ehvince

Reputation: 18395

Vue, Jest: how to mock element-ui components ? cannot find module element.css

My vue code calls element-ui modules:

// in main.js
import { Notification } from "element-ui";

At first, my test was throwing

Cannot find module 'Element' from 'test.js'

so I mocked the module with

jest.mock('element-ui', () => ({
  Element: jest.fn(),
}))

However it still errors out with

Cannot find module 'element-ui/lib/theme-default/element.css' from 'test.js'

and I don't know how to get passed this.

Any ideas ? Thanks.


If I import the element-ui components in my test.js:

ReferenceError: document is not defined

      at Object.<anonymous> (node_modules/element-ui/lib/utils/dom.js:22:39)
      at Object.<anonymous> (node_modules/element-ui/lib/utils/popup/popup-manager.js:9:12)
      at Object.<anonymous> (node_modules/element-ui/lib/utils/popup/index.js:14:21)

(Jest 21.2, vue-test-utils 1.0.0)

Upvotes: 1

Views: 3625

Answers (2)

Mike Mat
Mike Mat

Reputation: 692

What I did was to register all Element-UI components before every test file.

jest.config.js (https://jestjs.io/docs/en/configuration#setupfiles-array)

module.exports = { ..., setupFiles: ['./jest/eachTest.js'], ... }

eachTest.js

import Vue from 'vue' import Element from 'element-ui' Vue.use(Element, {})

Upvotes: 1

Ehvince
Ehvince

Reputation: 18395

This helped: https://github.com/eddyerburgh/vue-hackernews/

I now import all element-ui related components in the main.js, and I mock every method that calls one of its components:

beforeEach(() => {
    // Mock this method that calls a Notification element-ui component.
    vm.notifyWarning = jest.fn();
  })

Upvotes: 0

Related Questions