Jest not mocking module when using "doMock" to avoid hoisting - javascript

I'm trying to mock a class that creates and returns another class. I've got this:
const mockMethod = jest.fn();
const mockClassA = jest.fn<ClassA>(() => ({
method: mockMethod
}));
jest.mock("../src/ClassB", () => ({
ClassB: {
getClassA: () => new mockClassA()
}
}));
It gets caught out because of the hoisting, the mockClassA is undefined when jest is mocking `../src/ClassB".
I've read if you don't want hoisting, just use doMock instead:
When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
https://jestjs.io/docs/en/next/jest-object#jestdomockmodulename-factory-options
When I run with mock, I get TypeError: mockClassA is not a constructor, as mockClassA is undefined because the mock is hoisted above the definition for mockClassA.
When I change mock to doMock, it simply does not mock the module - it uses the real thing.
Edit: Declairing them in-line means I can't easily access the mocked methods for checking:
jest.mock("../src/ClassB", () => ({
ClassB: {
getClassA: () => ({
method: jest.fn()
})
}
}));
Because getClassA is a function, it's returning a separate instance of the object with method.
Edit 2: Ah! Managed to inline it like so:
jest.mock("../src/ClassB", () => {
const mockMethod: jest.fn();
return {
ClassB: {
getClassA: () => ({
method: mockMethod
})
}
};
});

I think you have 2 options here:
use jest.mock, inline the mockClassA and mockMethod, expose them in the mock and then import from '../src/ClassB'
use doMock, but use a dynamic require within your test case.

Related

How to mock global Object with Jest in React Native

I have the function:
const someFn = () => {
const keys = Object.keys(someObj);
// rest of function
}
In my unit test (with jest), I want to mock the return value of Object.keys:
test('some test', () => {
jest.mocked(Object.keys).mockReturnValue(['one', 'two']);
// rest of test
});
But that resulting the following error:
TypeError: jest.mocked(...).mockReturnValue is not a function
Usually It means that I need to first mock the export itself using jest.mock, but with global Object I'm not sure how to do it. I thought maybe:
global.Object = {
keys: jest.fn(),
}
But that doesn't seem to work at all.
Any idea how to solve this issue? thanks :)

How to test a mocked method that is used as a called function parameter -in a curry function- and not as a direct called function?

Here is the code to be tested, a small logger module, built as a composed object, this object has keys that are represented by curry functions. These curry functions have as first parameter a method that actually implements the method to be called (that requires a test).
Basically I would like to check that console.log or console.info are called.
logger.ts
const log = (logFn: () => void) => (message: any) => {
logFn(message)
}
const logger = {
debug: log(console.log),
info: log(console.info)
}
export default logger
logger.spec.ts
import logger from './logger'
describe('logger', () => {
describe('debug', () => {
it('sets a text as log output', () => {
const consoleSpy = jest.spyOn(console, 'log')
const text = 'Export is working properly'
logger.debug(text)
expect(consoleSpy).toHaveBeenCalledTimes(1) // failure
expect(consoleSpy).toHaveBeenCalledWith(text) // failure
console.log(text)
expect(consoleSpy).toHaveBeenCalledTimes(1) // success
expect(consoleSpy).toHaveBeenCalledWith(text) // success
})
})
})
But what happens is that, if I call console.log directly in my logger.ts, the test detects that the method is invoked, while, if I call my module method logFn that invokes indirectly console.log through a curry function, then the test does not detect it. I guess that the level of mocking is not reaching the proper scope. Anyway question is, is there a way to manage it? Thanks
it looks like the mocks are working correctly, because if you wrap the call console.log in an arrow function like debug: log((message: any) => console.log(message)), the test passes.

Is there a way to properly mock Reselect selectors for unit testing?

I'm having a pretty complex selectors structure in my project (some selectors may have up to 5 levels of nesting) so some of them are very hard to test with passing input state and I would like to mock input selectors instead. However I found that this is not really possible.
Here is the most simple example:
// selectors1.js
export const baseSelector = createSelector(...);
-
// selectors2.js
export const targetSelector = createSelector([selectors1.baseSelector], () => {...});
What I would like to have in my test suite:
beforeEach(() => {
jest.spyOn(selectors1, 'baseSelector').mockReturnValue('some value');
});
test('My test', () => {
expect(selectors2.targetSelector()).toEqual('some value');
});
But, this approach won't work as targetSelector is getting reference to selectors1.baseSelector during initialization of selectors2.js and mock is assigned to selectors1.baseSelector after it.
There are 2 working solutions I see now:
Mock entire selectors1.js module with jest.mock, however, it won't work if I'll need to change selectors1.baseSelector output for some specific cases
Wrap every dependency selectors like this:
export const targetSelector = createSelector([(state) => selectors1.baseSelector(state)], () => {...});
But I don't like this approach a lot for obvious reasons.
So, the question is next: is there any chance to mock Reselect selectors properly for unit testing?
The thing is that Reselect is based on the composition concept. So you create one selector from many others. What really you need to test is not the whole selector, but the last function which do the job. If not, the tests will duplicate each other, as if you have tests for selector1, and selector1 is used in selector2, then automatically you test both of them in selector2 tests.
In order to achieve:
less mocks
no need to specially mock result of composed selectors
no test duplication
test only the result function of the selector. It is accessible by selector.resultFunc.
So for example:
const selector2 = createSelector(selector1, (data) => ...);
// tests
const actual = selector2.resultFunc([returnOfSelector1Mock]);
const expected = [what we expect];
expect(actual).toEqual(expected)
Summary
Instead of testing the whole composition, and duplicating the same assertion, or mocking specific selectors outputs, we test the function which defines our selector, so the last argument in createSelector, accessible by resultFunc key.
You could achieve this by mocking the entire selectors1.js module, but also importing is inside test, in order to have access over the mocked functionality
Assuming your selectors1.js looks like
import { createSelector } from 'reselect';
// selector
const getFoo = state => state.foo;
// reselect function
export const baseSelector = createSelector(
[getFoo],
foo => foo
);
and selectors2.js looks like
import { createSelector } from 'reselect';
import selectors1 from './selectors1';
export const targetSelector = createSelector(
[selectors1.baseSelector],
foo => {
return foo.a;
}
);
Then you could write some test like
import { baseSelector } from './selectors1';
import { targetSelector } from './selectors2';
// This mocking call will be hoisted to the top (before import)
jest.mock('./selectors1', () => ({
baseSelector: jest.fn()
}));
describe('selectors', () => {
test('foo.a = 1', () => {
const state = {
foo: {
a: 1
}
};
baseSelector.mockReturnValue({ a: 1 });
expect(targetSelector(state)).toBe(1);
});
test('foo.a = 2', () => {
const state = {
foo: {
a: 1
}
};
baseSelector.mockReturnValue({ a: 2 });
expect(targetSelector(state)).toBe(2);
});
});
jest.mock function call will be hoisted to the top of the module to mock the selectors1.js module
When you import/require selectors1.js, you will get the mocked version of baseSelector which you can control its behaviour before running the test
For anyone trying to solve this using Typescript, this post is what finally worked for me:
https://dev.to/terabaud/testing-with-jest-and-typescript-the-tricky-parts-1gnc
My problem was that I was testing a module that called several different selectors in the process of creating a request, and the redux-mock-store state that I created wasn't visible to the selectors when the tests executed. I ended up skipping the mock store altogether, and instead I mocked the return data for the specific selectors that were called.
The process is this:
Import the selectors and register them as jest functions:
import { inputsSelector, outputsSelector } from "../store/selectors";
import { mockInputsData, mockOutputsData } from "../utils/test-data";
jest.mock("../store/selectors", () => ({
inputsSelector: jest.fn(),
outputsSelector: jest.fn(),
}));
Then use .mockImplementation along with he mocked helper from ts-jest\utils, which lets you wrap each selector and give custom return data to each one.
beforeEach(() => {
mocked(inputsSelector).mockImplementation(() => {
return mockInputsData;
});
mocked(outputsSelector).mockImplementation(() => {
return mockOutputsData;
});
});
If you need to override the default return value for a selector in a specific test, you can do that inside the test() definition like this:
test("returns empty list when output data is missing", () => {
mocked(outputsSelector).mockClear();
mocked(outputsSelector).mockImplementationOnce(() => {
return [];
});
// ... rest of your test code follows ...
});
I ran into the same problem. I ended up mocking the reselect createSelector with jest.mock to ignore all but the last argument (which is the core function you want to test) when it comes to testing. Overall this approach has served me well.
Problem I had
I had a circular dependency within my selector modules. Our code base is too large and we don't have the bandwidth to refactor them accordingly.
Why I used this approach?
Our code base has a lot of circular dependencies in the Selectors. And trying to rewrite and refactor them to not have circular dependencies are too much work. Therefore I chose to mock createSelector so that I don't have to spend time refactoring.
If your code base for selectors are clean and free of dependencies, definitely look into using reselect resultFunc. More documentation here: https://github.com/reduxjs/reselect#createselectorinputselectors--inputselectors-resultfunc
Code I used to mock the createSelector
// Mock the reselect
// This mocking call will be hoisted to the top (before import)
jest.mock('reselect', () => ({
createSelector: (...params) => params[params.length - 1]
}));
Then to access the created selector, I had something like this
const myFunc = TargetSelector.IsCurrentPhaseDraft;
The entire test suite code in action
// Mock the reselect
// This mocking call will be hoisted to the top (before import)
jest.mock('reselect', () => ({
createSelector: (...params) => params[params.length - 1]
}));
import * as TargetSelector from './TicketFormStateSelectors';
import { FILTER_VALUES } from '../../AppConstant';
describe('TicketFormStateSelectors.IsCurrentPhaseDraft', () => {
const myFunc = TargetSelector.IsCurrentPhaseDraft;
it('Yes Scenario', () => {
expect(myFunc(FILTER_VALUES.PHASE_DRAFT)).toEqual(true);
});
it('No Scenario', () => {
expect(myFunc(FILTER_VALUES.PHASE_CLOSED)).toEqual(false);
expect(myFunc('')).toEqual(false);
});
});

Jest 'TypeError: is not a function' in jest.mock

I'm writing a Jest mock, but I seem to have a problem when defining a mocked function outside of the mock itself.
I have a class:
myClass.js
class MyClass {
constructor(name) {
this.name = name;
}
methodOne(val) {
return val + 1;
}
methodTwo() {
return 2;
}
}
export default MyClass;
And a file using it:
testSubject.js
import MyClass from './myClass';
const classInstance = new MyClass('Fido');
const testSubject = () => classInstance.methodOne(1) + classInstance.name;
export default testSubject;
And the test:
testSubject.test.js
import testSubject from './testSubject';
const mockFunction = jest.fn(() => 2)
jest.mock('./myClass', () => () => ({
name: 'Name',
methodOne: mockFunction,
methodTwo: jest.fn(),
}))
describe('MyClass tests', () => {
it('test one', () => {
const result = testSubject()
expect(result).toEqual('2Name')
})
})
However, I get the following error:
TypeError: classInstance.methodOne is not a function
If I instead write:
...
methodOne: jest.fn(() => 2)
Then the test passes no problem.
Is there a way of defining this outside of the mock itself?
In my case, I had to mock a Node.js module. I'm using React and Redux in ES6, with Jest and Enzyme for unit tests.
In the file I'm using, and writing a test for, I'm importing the node modules as default:
import nodeModulePackage from 'nodeModulePackage';
So I needed to mock it as a default since I kept getting the error (0, _blah.default) is not a function..
My solution was to do:
jest.mock('nodeModulePackage', () => jest.fn(() => {}));
In my case, I just needed to override the function and make it return an empty object.
If you need to call a function on that node module, you'll do the following:
jest.mock('nodeModulePackage', () => ({ doSomething: jest.fn(() => 'foo') }));
I figured this out. It is to do with hoisting, see: Jest mocking reference error
The reason it had worked in a previous test, where I had done it, was because the testSubject was itself a class. This meant that when the testSubject was instantiated, it was after the variable declaration in the test file, so the mock had access to use it.
So in the above case it was never going to work.
Defining mockOne as an unassigned let and then initialising the variable inside the mocking function worked for me:
let mockFunction
jest.mock('./myClass', () => () => {
mockFunction = jest.fn(() => 2)
return {
name: 'Name',
methodOne: mockFunction,
methodTwo: jest.fn(),
}
}))
In my case, it was the importing, as described at Getting `TypeError: jest.fn is not a function` (posting here because my problem showed in jest.mock, so I looked here first).
The basic problem was that someone had put in
const jest = require('jest');
But that is wrong (should be jest-mock instead of jest). This had worked in Node.js 10 with the line as originally put. It did not work in Node.js 14. I'm guessing that they used different versions of Jest, perhaps indirectly (other packages needed updated for 14).
const jest = require('jest-mock');
Also, in a test file, it will probably already be done for you, so you don't need to require anything. The file will run properly without that line.
Linting may give an error with that line omitted, but that can be fixed with
/* global jest */
or if you're already doing that with expect,
/* global expect, jest */
The linter seemed happy when that line appeared either after or before jest was first used. You may choose order based on readability rather than by functional requirement if your linter works the same way.
In my case it was from the module.exports.
Instead of writing
module.exports = {sum: sum};
Write
module.exports = sum;
Note: sum is a function that adds 2 numbers
In case anyone is still facing a similar issue, to resolve the failing tests I had to return a mocked function like so:
const tea = TeamMaker.makeTea();
tea(); // TypeError: tea is not a function
jest.mock('url/to/TeamMaker', () => ({ makeTea: jest.fn(() => jest.fn) })); // tests passed
For the other Jest newbies out there, if you mock multiple functions from the same package or module like this:
jest.mock(
'pathToModule',
() => ({
functionA: jest.fn(() => {
return 'contentA';
}),
})
);
jest.mock(
'pathToModule',
() => ({
functionB: jest.fn(() => {
return 'contentB';
}),
})
);
The second mock will override the first, and you'll end up with functionA is not a function.
Just combine them if they're both coming from the same module.
jest.mock(
'samePathToModule',
() => ({
functionA: jest.fn(() => {
return 'contentA';
}),
functionB: jest.fn(() => {
return 'contentB';
}),
})
);
For me, it was the jest config.
Because my project was initially in .js and was upgrade to .ts.
So the class I tested was in .ts but my jest.config.js was config for .jsfile.
See below my new config :
module.exports = {
...
collectCoverageFrom: ['src/**/*.{ts,js,jsx,mjs}'],
...
testMatch: [
'<rootDir>/src/**/__tests__/**/*.{ts,js,jsx,mjs}',
'<rootDir>/src/**/?(*.)(spec|test).{ts,js,jsx,mjs}',
]
};
In my case, it was the way i was exporting the files that was the issue.
The file i was trying to mock was being exported like:
export const fn = () => {};
The mocked file i wrote was being exported like:
const fn = () => {};
export default fn;
Once i made sure that the mocked file was also being exported like the file to be mocked, i didn't have this issue
following is the answer which worked for me
import {testSubject} from '../testsubject';
describe('sometest',(){
it('some test scenario',()=>{
testSubject.mockReturnValue(()=>jest.fn);
})
})
I am writing my version in case it helps someone.
I was facing error while mocking firebase-admin.
I jest-mocked firebase-admin like below:
jest.mock('firebase-admin');
But I started getting following error:
firebase_admin_1.default.messaging is not a function
It was coming because in the app code, I had used firebase-admin like this:
await admin.messaging().send(message)
(message is an instance of TokenMessage)
The problem was that I was not mocking the member variables and member methods. Here it was the member method messaging and a nested member method within messaging called send. (See that messaging method is called on admin and then send is called on the value of admin.messaging()). All that was needed was to mock these like below:
jest.mock('firebase-admin', () => ({
credential: {
cert: jest.fn(),
},
initializeApp: jest.fn(),
messaging: jest.fn().mockImplementation(() => {
return {
send: jest
.fn()
.mockReturnValue('projects/name_of_project/messages/message_id'),
};
}),
}));
(Note that I have also mocked other member variables/methods as per my original requirement. You would probably need these mocks as well)
IT HAS TO BE EXPORTED.
like node function.
e.g. helper.js has myLog function
at the end,
module.exports = {
sleep,
myLog
};
now spec file can import and call them.
No tsx or jest.config.js changes...

Cannot mock a module with jest, and test function calls

I create a project using create-app-component, which configures a new app with build scripts (babel, webpack, jest).
I wrote a React component that I'm trying to test. The component is requiring another javascript file, exposing a function.
My search.js file
export {
search,
}
function search(){
// does things
return Promise.resolve('foo')
}
My react component:
import React from 'react'
import { search } from './search.js'
import SearchResults from './SearchResults'
export default SearchContainer {
constructor(){
this.state = {
query: "hello world"
}
}
componentDidMount(){
search(this.state.query)
.then(result => { this.setState({ result, })})
}
render() {
return <SearchResults
result={this.state.result}
/>
}
}
In my unit tests, I want to check that the method search was called with the correct arguments.
My tests look something like that:
import React from 'react';
import { shallow } from 'enzyme';
import should from 'should/as-function';
import SearchResults from './SearchResults';
let mockPromise;
jest.mock('./search.js', () => {
return { search: jest.fn(() => mockPromise)};
});
import SearchContainer from './SearchContainer';
describe('<SearchContainer />', () => {
it('should call the search module', () => {
const result = { foo: 'bar' }
mockPromise = Promise.resolve(result);
const wrapper = shallow(<SearchContainer />);
wrapper.instance().componentDidMount();
mockPromise.then(() => {
const searchResults = wrapper.find(SearchResults).first();
should(searchResults.prop('result')).equal(result);
})
})
});
I already had a hard time to figure out how to make jest.mock work, because it requires variables to be prefixed by mock.
But if I want to test arguments to the method search, I need to make the mocked function available in my tests.
If I transform the mocking part, to use a variable:
const mockSearch = jest.fn(() => mockPromise)
jest.mock('./search.js', () => {
return { search: mockSearch};
});
I get this error:
TypeError: (0 , _search.search) is not a function
Whatever I try to have access to the jest.fn and test the arguments, I cannot make it work.
What am I doing wrong?
The problem
The reason you're getting that error has to do with how various operations are hoisted.
Even though in your original code you only import SearchContainer after assigning a value to mockSearch and calling jest's mock, the specs point out that: Before instantiating a module, all of the modules it requested must be available.
Therefore, at the time SearchContainer is imported, and in turn imports search , your mockSearch variable is still undefined.
One might find this strange, as it would also seem to imply search.js isn't mocked yet, and so mocking wouldn't work at all. Fortunately, (babel-)jest makes sure to hoist calls to mock and similar functions even higher than the imports, so that mocking will work.
Nevertheless, the assignment of mockSearch, which is referenced by the mock's function, will not be hoisted with the mock call. So, the order of relevant operations will be something like:
Set a mock factory for ./search.js
Import all dependencies, which will call the mock factory for a function to give the component
Assign a value to mockSearch
When step 2 happens, the search function passed to the component will be undefined, and the assignment at step 3 is too late to change that.
Solution
If you create the mock function as part of the mock call (such that it'll be hoisted too), it'll have a valid value when it's imported by the component module, as your early example shows.
As you pointed out, the problem begins when you want to make the mocked function available in your tests. There is one obvious solution to this: separately import the module you've already mocked.
Since you now know jest mocking actually happens before imports, a trivial approach would be:
import { search } from './search.js'; // This will actually be the mock
jest.mock('./search.js', () => {
return { search: jest.fn(() => mockPromise) };
});
[...]
beforeEach(() => {
search.mockClear();
});
it('should call the search module', () => {
[...]
expect(search.mock.calls.length).toBe(1);
expect(search.mock.calls[0]).toEqual(expectedArgs);
});
In fact, you might want to replace:
import { search } from './search.js';
With:
const { search } = require.requireMock('./search.js');
This shouldn't make any functional difference, but might make what you're doing a bit more explicit (and should help anyone using a type-checking system such as Flow, so it doesn't think you're trying to call mock functions on the original search).
Additional note
All of this is only strictly necessary if what you need to mock is the default export of a module itself. Otherwise (as #publicJorn points out), you can simply re-assign the specific relevant member in the tests, like so:
import * as search from './search.js';
beforeEach(() => {
search.search = jest.fn(() => mockPromise);
});
In my case, I got this error because I failed to implement the mock correctly.
My failing code:
jest.mock('react-native-some-module', mockedModule);
When it should have been an arrow function...
jest.mock('react-native-some-module', () => mockedModule);
When mocking an api call with a response remember to async() => your test and await the wrapper update. My page did the typical componentDidMount => make API call => positive response set some state...however the state in the wrapper did not get updated...async and await fix that...this example is for brevity...
...otherImports etc...
const SomeApi = require.requireMock('../../api/someApi.js');
jest.mock('../../api/someApi.js', () => {
return {
GetSomeData: jest.fn()
};
});
beforeEach(() => {
// Clear any calls to the mocks.
SomeApi.GetSomeData.mockClear();
});
it("renders valid token", async () => {
const responseValue = {data:{
tokenIsValid:true}};
SomeApi.GetSomeData.mockResolvedValue(responseValue);
let wrapper = shallow(<MyPage {...props} />);
expect(wrapper).not.toBeNull();
await wrapper.update();
const state = wrapper.instance().state;
expect(state.tokenIsValid).toBe(true);
});

Categories