Search code examples
vue.jsjestjsvue-test-utils

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)


Solution

  • 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();
      })