Do I Need To Mock The Required Module In Jest Testing
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";
jest.dontMock(__path__);
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]];
expect(Utils.FOO(testInput)).toEqual(expectedOutput);
});
});
});
Answer
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.
Edit
As @pgericson has noted in the comments, Jest no longer automocks as of jest 15. Jasmine spies can be used in lieu of automocks.
Related Questions
- → React components not works in RequireJS+Jasmine unit tests
- → multiCapabilities and jasmine focused tests
- → how to include module in angualar js to remove error module not found?
- → React shallow rendering generates component with type == Function instead of type == <ComponentName>
- → Jasmine return rejected in a mocked factory's promise
- → requirejs confilcts with define/require functions
- → Error when trying to unit test a basic service on AngularJS
- → How to write a leap year algorithm in Javascript with TDD?
- → Karma unit testing: Module name "react" has not been loaded yet for context: _. Use require([])
- → how to use HttpBackend for the $http
- → Writing Unit Tests for Form Elements
- → Angular Jasmine SpyOn $resource Handle Errors
- → Vue.js - Data lost in karma/phantomjs tests