Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass externals from webpack to jest?

I've got this webpack config as part of my grunt building process:

module.exports = {
options: {
    output: {
        path: path.resolve('../ui/static/js'),
        filename: '[name].js',
        chunkFilename: '[id].[name].js',
        libraryTarget: 'amd',
        library: '[name]'
    },

    externals: [
        'jquery',
        'lodash',
        'backbone',
        'backbone.layoutmanager',
        'moment',
        'spin',
        'lib/select2.min',
        'dispatcher'
    ],
    resolve: {
        root: path.resolve('../ui'),
        alias: {
            'jst': 'static/jst'
        }
    }

We are moving to react now, and I need to import some files in my test files, where this dependencies included, but jest can not find them:

Cannot find module 'lib/select2.min' from 'helpers.js'
Cannot find module 'jst/templates_jst' from 'base-view.js

What is the right way to resolve this issue?

like image 952
lasfin Avatar asked Dec 07 '16 13:12

lasfin


3 Answers

Here's what works today with [email protected] and [email protected]. Assuming this is your externals webpack config:

externals: {
  react: {
    root: 'React',
    commonjs2: 'react',
    commonjs: 'react',
    amd: 'react',
  },
}

You'll need to map each external library to be properly resolved in your jest config like so:

moduleNameMapper: {
  "^./react": path.resolve(__dirname, 'node_modules/react'),
}

While debugging your issue, be sure to check what your built component file looks like. You want to be sure that you see something like:

!function(e,t){if("object"==typeof exports&&"object"==typeof module)
module.exports=t(require("react"));
else if("function"==typeof define&&define.amd)define(["react"],t);
else{var n="object"==typeof exports?t(require("react")):t(e.React);

Important bit being react for commonjs and amd, and React for the browser.

like image 159
Maciej Gurban Avatar answered Oct 23 '22 23:10

Maciej Gurban


For my case using the __mocks__ would be a bit verbose but I used the

jest.mock('myModule', () => {/* module impl */}, {virtual: true})

In case the __mocks__ suggestion is to verbose for you too check out the docs here

like image 26
Dusan Turajlic Avatar answered Oct 23 '22 23:10

Dusan Turajlic


You need to mock the external lib.

Example with jquery:

  1. Create a __mocks__ folder in the same level of __test__ folder.
  2. Inside that, create a file with the same name of the dependency, in this case, jquery (jquery.js).
  3. Inside the test file, use jest.mock function to reference the mock external dependency: jest.mock('jquery');

from jest the docs: https://facebook.github.io/jest/docs/manual-mocks.html

Hope it helps.

like image 25
Horacio Alexandre Fernandes Avatar answered Oct 23 '22 23:10

Horacio Alexandre Fernandes