Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to load AMD modules through Jest

I'm trying to use Jest for unit testing my React code but I'm also using requirejs and so all my React code is in AMD modules. It obviously works well in browser but when I run Jest tests, it can't load my AMD modules. Initially it was giving me error for define saying define is not defined, so I used amdefine by Requirejs to fix it. Now it can understand define but still can't load my module.

like image 226
Rahul Dole Avatar asked Sep 27 '22 03:09

Rahul Dole


3 Answers

I ran into same problem, so I went ahead and mocked my dependency at the top of test file:

jest.mock('../../components/my-button', () => {
  // mock implementation
})

import MyButton from '../../components/my-button';

This way, when MyButton is loaded, its dependency is already mocked, so it won't try to load the RequireJS module.

like image 99
Peter Avatar answered Oct 16 '22 17:10

Peter


There's no official Facebook support for requirejs in Jest yet. But's planned. Look this thread: https://github.com/facebook/jest/issues/17

Also in this thread Sterpe posted a plugin he wrote to do it (but I didn't try it): https://github.com/sterpe/jest-requirejs

like image 1
Dani torrens Avatar answered Oct 16 '22 15:10

Dani torrens


I had the same problem today and here is what I've done :

Module.js

(()=> {
    const dependencies = ['./dep.js'];
    const libEnv = function (dep) {

        // lib content
        function theAnswer (){
            return dep.answer;
        }

        return {theAnswer}; // exports

    };
    //AMD & CommonJS compatibility stuff
    // CommonJS
    if (typeof module !== 'undefined' && typeof require !== 'undefined'){
        module.exports = libEnv.apply(this, dependencies.map(require));
        module.exports.mockable = libEnv; // module loader with mockable dependencies
    }
    // AMD
    if (typeof define !== 'undefined') define(dependencies, libEnv);
})();

You will found all needed files on my github repository to test :

  • in browser for requirejs

  • with node for jest

https://github.com/1twitif/testRequireJSAmdModulesWithJest

like image 1
1000i100 Avatar answered Oct 16 '22 15:10

1000i100