Do I Need To Mock The Required Module In Jest Testing

- 1 answer

I had a mixin/Utils.js to test, where underscore is required and used in the module. Something like:

var _ = require('underscore');
var Utils = {

   foo: function(arrayOfArray) {
    return _.sortBy(arrayOfArray, function(array) {

      return -1 * array[1].length;

    }) || {};


module.exports = Utils;

When I tried to use Jest to test it, I made something like below. But the test failed. I had a feeling that was because I didn't mock the underscore. But how should I mock that? And in general if the module has dependencies like underscore, how should I set the mock correctly and test the module?

 var __path__ = "PATH_TO/mixins/Utils.js";


 describe("Test for mixins/Utils.js", function() {

    var Utils;

    beforeEach(function() {
    Utils = require(__path__);

   describe("countInversion", function() {

    it('Passing in [[0, [1,2]], [1, [1,2,3]]] and should get [[1, [1,2,3]]],[0, [1,2]] ', function()        {
        var testInput = [[0, [1,2]], [1, [1,2,3]]];
        var expectedOutput = [[1, [1,2,3]]],[0, [1,2]]; 




Jest mocks everything by default so you you actually do not want to mock underscore if your unit test depends on functionality in underscore. You should either add jest.dontMock('underscore') to your test, or include it in the unmockedModulePathPatterns property of your jest config to get the output you expect.


As @pgericson has noted in the comments, Jest no longer automocks as of jest 15. Jasmine spies can be used in lieu of automocks.