My mocked utilFunction isn't being used and adding logging to the factory function shows that it's never called. I've already tried searching for jest.mock not working with relative paths and jest.mock not being called for Typescript thinking that it might be related to the mix of JS tests and TS source code or to the different module paths used in the source vs test code.
Code being tested:
// src/foo/fooModule.ts
import { utilFunction } from '../util'
export const foo = () => {
return utilFunction()
}
Test code:
// test/fooModule.test.js
const { foo } = require('../src/foo/fooModule')
jest.mock('../src/util', () => {
return { utilFunction: () => 'mocked' };
});
describe('fooModule tests', () => ...)
The jest.mock call needs to be moved above the imports:
// test/fooModule.test.js
jest.mock('../src/util', () => {
return { utilFunction: () => 'mocked' };
});
const { foo } = require('../src/foo/fooModule')
describe('fooModule tests', () => ...)
My last experience working with Jest prior to this was in a project where the tests were also written in Typescript and babel-jest was used. babel-jest includes babel-jest-hoist which hoists the jest mocks above any imports automatically, so I didn't previously have to worry about the ordering.
I wonder if there is a better way to disable console errors inside a specific Jest test (i.e. restore the original console before/after each test).
Here is my current approach:
describe("Some description", () => {
let consoleSpy;
beforeEach(() => {
if (typeof consoleSpy === "function") {
consoleSpy.mockRestore();
}
});
test("Some test that should not output errors to jest console", () => {
expect.assertions(2);
consoleSpy = jest.spyOn(console, "error").mockImplementation();
// some function that uses console error
expect(someFunction).toBe("X");
expect(consoleSpy).toHaveBeenCalled();
});
test("Test that has console available", () => {
// shows up during jest watch test, just as intended
console.error("test");
});
});
Is there a cleaner way of accomplishing the same thing? I would like to avoid spyOn, but mockRestore only seems to work with it.
For particular spec file, Andreas's is good enough. Below setup will suppress console.log statements for all test suites,
jest --silent
(or)
To customize warn, info and debug you can use below setup
tests/setup.js or jest-preload.js configured in setupFilesAfterEnv
global.console = {
...console,
// uncomment to ignore a specific log level
log: jest.fn(),
debug: jest.fn(),
info: jest.fn(),
// warn: jest.fn(),
// error: jest.fn(),
};
jest.config.js
module.exports = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],
};
If you want to do it just for a specific test:
beforeEach(() => {
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
As every test file runs in its own thread there is no need to restore it if you want to disable it for all test in one file. For the same reason you can also just write
console.log = jest.fn()
expect(console.log).toHaveBeenCalled();
I found that the answer above re: suppressing console.log across all test suites threw errors when any other console methods (e.g. warn, error) were called since it was replacing the entire global console object.
This somewhat similar approach worked for me with Jest 22+:
package.json
"jest": {
"setupFiles": [...],
"setupTestFrameworkScriptFile": "<rootDir>/jest/setup.js",
...
}
jest/setup.js
jest.spyOn(global.console, 'log').mockImplementation(() => jest.fn());
Using this method, only console.log is mocked and other console methods are unaffected.
To me a more clear/clean way (reader needs little knowledge of the jest API to understand what is happening), is to just manually do what mockRestore does:
// at start of test you want to suppress
const consoleLog = console.log;
console.log = jest.fn();
// at end of test
console.log = consoleLog;
beforeAll(() => {
jest.spyOn(console, 'log').mockImplementation(() => {});
jest.spyOn(console, 'error').mockImplementation(() => {});
jest.spyOn(console, 'warn').mockImplementation(() => {});
jest.spyOn(console, 'info').mockImplementation(() => {});
jest.spyOn(console, 'debug').mockImplementation(() => {});
});
Here's all the lines you may want to use. You can put them right in the test:
jest.spyOn(console, 'warn').mockImplementation(() => {});
console.warn("You won't see me!")
expect(console.warn).toHaveBeenCalled();
console.warn.mockRestore();
Weirdly the answers above (except Raja's great answer but I wanted to share the weird way the others fail and how to clear the mock so no one else wastes the time I did) seem to successfully create the mock but don't suppress the logging to the console.
Both
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
and
global console = {
warn: jest.fn().mockImplementation(() => {});
}
successfully install the mock (I can use expect(console.warn).toBeCalledTimes(1) and it passes) but it still outputs the warning even though the mock implementation seemingly should be replacing the default (this is in a jsdom environment).
Eventually I found a hack to fix the problem and put the following in the file loaded with SetupFiles in your config (note that I found sometimes global.$ didn't work for me when putting jquery into global context so I just set all my globals this way in my setup).
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {});
const consoleLog = jest.spyOn(console, 'log').mockImplementation(() => {});
const consoleDebug = jest.spyOn(console, 'debug').mockImplementation(() => {});
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
Object.defineProperty(global, 'console', {value: {
warn: consoleWarn,
log: consoleLog,
debug: consoleDebug,
error: consoleError}});
It feels ugly and I then have to put code like the following in each test file since beforeEach isn't defined in the files referenced by SetupFiles (maybe you could put both in SetupFilesAfterEnv but I haven't tried).
beforeEach(() => {
console.warn.mockClear();
});
Since jest.spyOn doesn't work for this (it may have in the past), I resorted to jest.fn with a manual mock restoration as pointed out in Jest docs. This way, you should not miss any logs which are not empirically ignored in a specific test.
const consoleError = console.error
beforeEach(() => {
console.error = consoleError
})
test('with error', () => {
console.error = jest.fn()
console.error('error') // can't see me
})
test('with error and log', () => {
console.error('error') // now you can
})
If you are using command npm test to run test then change the test script in package.json like below
{
....
"name": "....",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest --silent", // add --silent to jest in script like this
"lint": "eslint ."
},
...
}
Or else you can directly run command npx jest --silent to get rid of all logs and errors when testing
Kudos to #Raja's top answer. Here is what I am using (I would comment, but can't share a multi-line code block in a comment).
With jest v26, I'm getting this error:
We detected setupFilesAfterEnv in your package.json.
Remove it from Jest configuration, and put the initialization code in src/setupTests.js:
This file will be loaded automatically.
Therefore, I had to remove the setupFilesAfterEnv from my jest config, and add this to src/setupTests.js
// https://stackoverflow.com/questions/44467657/jest-better-way-to-disable-console-inside-unit-tests
const nativeConsoleError = global.console.error
global.console.error = (...args) => {
if (args.join('').includes('Could not parse CSS stylesheet')) {
return
}
return nativeConsoleError(...args)
}
Another approach is to use process.env.NODE_ENV. This way one can selectively choose what to show (or not) while running tests:
if (process.env.NODE_ENV === 'development') {
console.log('Show output only while in "development" mode');
} else if (process.env.NODE_ENV === 'test') {
console.log('Show output only while in "test" mode');
}
or
const logDev = msg => {
if (process.env.NODE_ENV === 'development') {
console.log(msg);
}
}
logDev('Show output only while in "development" mode');
This will require this configuration to be placed on package.json:
"jest": {
"globals": {
"NODE_ENV": "test"
}
}
Note that this approach is not a direct solution to the original question, but gives the expected result as long as one has the possibility to wrap the console.log with the mentioned condition.
I have a virtual javascript file in a Jest unit test with the path '/widgets/1.0.js'. I have mocked the fs module to simulate its existence.
Now i would like to dynamically load it to invoke a method 'foo()'. I thought it would be a case of using a virtual mock:
index.test.js
jest.mock('/widgets/1.0.js', () => {foo: jest.fn(() => {console.log('foo!')})}, {virtual: true});
The code which calls the mock:
index.js
let module = require('/widgets/1.0.js');
module.foo();
When i run the test:
Cannot find module '/widgets/1.0.js' from 'index.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:151:17)
at processWidgets (src/index.js:115:2418)
at Object.<anonymous> (src/__tests__/index.test.js:99:73)
I think it should be possible. Any ideas?
thanks!
It appears to be a problem with the module path. This works:
index.test.js
jest.mock('1.0', () => {
return {
foo: () => {return 42;}
}
}, {virtual: true});
index.js
const module = require('1.0');
let retval = module.foo();
console.log('retval: ', retval);
If i use '/widgets/1.0' it does not. Hope it helps..
I'm setting up ES6 unit tests in my project and I am having some trouble making them work with libraries. I thought I'd use jQuery just as a test to try and make it work. Without libraries, the tests work.
Note that jQuery is imported into my main.js file so it is available throughout the project.
My JS file looks like this:
class Test {
constructor(options) {
this.init();
}
init() {
$('.test-div').addClass('test');
}
sayHello() {
return 'hello world!';
}
}
export default Test;
And the test looks like this:
import jsdom from 'mocha-jsdom';
import chai from 'chai';
import Test from './test';
chai.should();
describe('Frequency', () => {
var $;
jsdom();
before(() => {
$ = require('jquery');
})
it('should output hello world', () => {
const test = new Test();
test.sayHello().should.equal('hello world!');
});
});
If I remove the init() function, the test works. However, the before function doesn't seem to import jQuery for the test. The error I receive in the console is as follows:
ReferenceError: $ is not defined
at Frequency.init
I copied your code and got it to work by modifying the before hook to:
before(() => {
$ = require('jquery');
global.$ = $;
});
If you read mocha-jsdom's documentation you'll see that it puts in the global space symbols like window and document. When you load jquery, it finds window and adds itself as window.$. In a browser, this also makes $ visible in the global space because window is the global space. In Node, however, the global space is global, and so you have to put $ in it yourself.
You need to declare global variables in a custom setup.js:
package.json:
"scripts": {
"unit": "mocha-webpack --webpack-config webpack.test.js test/unit/*.spec.js --require test/setup.js"
},
or if you don't use webpack:
"scripts": {
"unit": "mocha test/unit/*.spec.js --require test/setup.js"
},
test/setup.js:
let jsdom = require('jsdom-global')();
let jQuery = require("jquery");
global.jQuery = jQuery;
global.$ = jQuery;
//https://github.com/vuejs/vue-cli/issues/2128
window.Date = Date;
Then you can use them as usual in your test scripts.
I have an app with react and redux. My test engine is - Chai
In my reducer (src/my_reducer.js), I try to get token from localStorage like this:
const initialState = {
profile: {},
token: window.localStorage.getItem('id_token') ? window.localStorage.getItem('id_token') : null,
}
In my tests file (test/reducer_spec.js) I have import 'my_reducer' before test cases:
import myReducer from '../src/my_reducer'
And I have an error, if I try to run test - localStorage (or window.localStorage) - undefined.
I need to mock localStorage? If I need, where is the place for it?
I presume you are running your tests with mocha?
mocha tests run in node.js, and node.js does not have a global window variable. But you can easily create one in your tests:
global.window = {};
You can even add the localStorage to it immediately:
global.window = { localStorage: /* your mock localStorage */ }
The mock depends on what you store in your local storage, but for the example code above this might be a reasonable mock object:
var mockLocalStorage = {
getItem: function (key) {
if( key === 'id_token' ){ return /* a token object */; }
return null;
}
}
Of course, for different tests you can have different mocks, e.g. another mock might always return null to test the case that the key cannot be found.
I solve problem with mock-local-storage
My run test command is:
mocha -r mock-local-storage --compilers js:babel-core/register --recursive
For testing purposes I recommend not to make any calls which may have side effects or call external modules in declarations.
Because requiring / importing your reducer implicitly calls window.localStorage.getItem(...) clean testing gets hard.
I'd suggest to wrap your initialization code with a init method so nothing happens if you require/import your module before calling init. Then you can use beforeEach afterEach to cleanly setup mocks/sandboxes.
import myReducer from '../src/my_reducer'
describe('with faked localStorage', function() {
var sandbox
beforeEach(function() {
sandbox = sinon.sandbox.create()
// fake window.localStorage
})
afterEach(function() {
sandbox.restore()
})
describe('the reducer', function() {
before(function() {
myReducer.init()
})
})
})
The second best solution is to postpone the import and use require within the before test hook.
describe('with fake localStorage', function() {
var sandbox
beforeEach(function() {
sandbox = sinon.sandbox.create()
// fake window.localStorage
})
afterEach(function() {
sandbox.restore()
})
describe('the reducer', function() {
var myReducer
before(function() {
myReducer = require('../src/my_reducer')
})
})
})
It is because you are not running Chai in a browser environment.
Try:
// Make sure there is a window object available, and that it has localstorage (old browsers don't)
const initialState = {
profile: {},
// window.localStorage.getItem('id_token') will return null if key not found
token: window && window.localStorage ? window.localStorage.getItem('id_token') : null,
}