Accessing .mock property of an automocked function - jestjs

I have this code:
import * as a from 'a-a';
jest.mock('a-a');
describe('a-a', () => {
beforeAll(async () => {
const x = await a.x(1); // Calls the mock
console.log(x); // 1
console.log(a.x.mock) // Undefined
});
});
The mock function is:
export async function x(data) {
cache.push(data);
console.log('HERE'); // this is printed
return data;
}
The mock of the module is in the __mocks__ directory.
The a.x() calls the mocked function, but a.x.mock is undefined.
How is that possible? Where is the .mock property?

So, after some investigation I found out that the functions declared in the __mocks__ directory aren't wrapped by jest.fn() by default.
Personally I find the thing a bit confusing.
So you can do both
function x(data) {
cache.push(data);
return cache;
}
jest.mock('a-a', () => ({x: x}))
if you do everything in the same file, or
jest.mock('a-a');
and then in the __mocks__/a-a.js file
export const x = jest.fn(async (data) => {
cache.push(data);
return cache;
});

Related

Typescript import module.exports sub function

I'm using mocha to test a function and I'm facing an error while running the test file.
The file structure is as follows
server
|-test
| |-customer.test.ts
|-customer.js
This is the customer.js file function
module.exports = (instance) => {
instance.validate = async (ctx) => {
// some code here
}
}
This is the mocha test case file customer.test.ts
const instance = require("../customer")
/* eslint-disable no-undef */
describe('customer', () => {
describe('/POST customers', () => {
it('Create Buy customer', (done) => {
instance.validate({
})
done();
});
})
});
But when I run the file using the command mocha .\customer.test.ts it shows me the following error
TypeError: instance.validate is not a function
How do I make the above function execute?
What you're exporting and what you're doing with the import don't match. The problem is (probably) the export. What you have is this:
module.exports = (instance) => {
instance.validate = async (ctx) => {
// some code here
}
}
That exports a function that, when called, will add a validate method to the object that you pass to it. It does not export an object with a validate method, that would look like this:
module.exports = {
validate: async (ctx) => {
// some code here
},
};
So you need to either fix the export (which I suspect is the problem), or (if the export is really meant to do that), test what it actually does by passing in an object and then checking that, after the call, the object has a validate method.

Unmock function after mockimplementation

I'm having a bit of trouble unmocking a function.
I first mock it and now I can't unmock it
//myClass.js
class myClass {
static check(v1,v2) {
return v1 > v2;
}
static async getinfo(v1,v2) {
if (this.check(v1,v2)) {
return await get('api.google.com');
}
return [];
}
}
//myclass.spec.js
describe('Testing myClass', () => {
describe('testing processing', () => {
it('should return result', () => {
const mockPatch = jest.fn().mockImplementation((version, solution) => false);
myClass.check = mockCheck;
try {
const result = await myClass.getinfo(1,2);
expect(result).toBe.([]);
}catch(e) {
throw e;
}
})
})
describe('Testing check', () => {
it('should return true', () => {
expect(myClass.check(2,1)).toBe.true
})
})
})
I already try with
myClass.check.mockRestore()
beforeEach(() => {myClass.check.mockRestore()})
jest.unmock('./myClass.js)
Is there anyway I can solve this? I read all the jest doc and i couldn't find anything
Methods should never be mocked by reassigning them, there is no way how Jest could restore their original implementation this way.
This should always be done with spyOn:
jest.spyOn(myClass, 'check').mockReturnValue(false)
This way a method can be restored with restoreMock or restoreAllMocks. This should be preferably enabled globally in Jest configuration.
I'm assuming that what you're hoping to do is to mock an implementation for use in a specific test, but then have your other tests function without the mocking.
If so, I think you could use the module mocking strategy in conjunction with mockReturnValueOnce.
Be sure to import your module at the top of your tests, then to call jest.mock with the same path. After that, you should be able to call myClass.check.mockReturnValueOnce, and it will be mocked until the next time it is called. After that, it will function normally 👍

spyOn #react-native-firebase/analytics methods

Basically, I want to make sure the methods of analytics are called with certain properties but so far it is not working:
Cannot spy the logAppOpen property because it is not a function; undefined given instead
the library is successfully mocked since I can see console log out of my jest.fn():
jest.mock('#react-native-firebase/analytics', () => {
return () => ({
logAppOpen: jest.fn(() => console.log('mocked fun called')), //===>shown correctly
})
})
My class is:
import analytics from '#react-native-firebase/analytics';
export default class GA {
appStarted = async () =>{
console.log('appStarted called'); //==> showing
await analytics().logAppOpen();
}
}
my test:
it("should log app starting", async () =>{
const spy = jest.spyOn(analytics, 'logAppOpen') //===>FAILS HERE
congst ga = new GA();
await ga.appStarted();
expect(spy).toHaveBeenCalled();
})
but in my test: console.log(analytics) does show an empty object {}
It's analytics().logAppOpen() while jest.spyOn tries to spy on analytics.logAppOpen which doesn't exist.
For lazily evaluated spied functions it's easier to expose them as variables:
const mockLogAppOpen = jest.fn();
jest.mock('#react-native-firebase/analytics', () => {
return jest.fn()
.mockReturnValue({ logAppOpen: mockLogAppOpen });
});
This way it can be accessed for call assertions. There's no need for jest.spyOn for a function that is already a spy.

Jest: child_process.exec.mockImplentation is not a function

I have a function that uses the child_process.exec function:
//serverUtils.js:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
async getUpstreamRepo() {
try {
const forkConfig = (await exec('git remote get-url upstream')).stdout;
let upstreamRepo = forkConfig.replace('git#github.com:', '');
upstreamRepo = upstreamRepo.replace(/\r?\n|\r/g, '');
return upstreamRepo;
} catch (error) {
console.error(error);
throw error;
}
},
After looking at this SO post, I tried to mock the exec call like so:
//serverUtils.test.js:
const child_process = require('child_process');
jest.mock('child_process')
describe('Test Class', () => {
....
it('check upstream repo', async () => {
child_process.exec.mockImplentation(jest.fn().
mockReturnValueOnce('git#github.com:mock/url.git'))
await expect(serverScript.getUpstreamRepo()).
resolves.toEqual('mock/url.git');
});
}
However, I get child_process.exec.mockImplentation is not a function
As the linked post explains, "Jest documentation says that when mocking Node's core modules calling jest.mock('child_process') is required." -- which I clearly do.
The error you are seeing is because you are calling mockImplentation instead of mockImplementation. Unfortunately, when you correct that typo the test still will not pass.
This is because you are calling promisify on exec method, allowing it to be used as a promise. What promisify does under the hood is transform from an asynchronous callback based function (where the callback is placed at last parameter and is called with error as first parameter and data as second) to a promise based function.
So, in order for the promisify method to work, you will have to mock the exec method so that it calls the callback parameter in order for the promise to resolve.
Also, note that you are reading the stdout parameter from the result of the exec call, so in the returned data you will have to send an object with that property.
Having all that into account:
it('check upstream repo', async () => {
child_process.exec.mockImplementation((command, callback) => {
callback(null, { stdout: 'git#github.com:mock/url.git' });
});
await expect(serverScript.getUpstreamRepo()).
resolves.toEqual('mock/url.git');
});
Another posible solution is to directly mock the promisify method:
jest.mock('util', () => ({
promisify: jest.fn(() => {
return jest.fn().mockResolvedValue({ stdout: 'git#github.com:mock/url.git' });
})
}));
describe('Test Class', () => {
it('check upstream repo', async () => {
await expect(serverScript.getUpstreamRepo()).
resolves.toEqual('mock/url.git');
});
});

jest mocking functions without passing as a callback

I have some code like:
module.exports = {
idCheck: function(errors) {
errors.some( (error) => {
if (error.parentSchema.regexp === '/^((?!\\bMyId\\b).)*$/i') {
this._recordError('IDCHECK');
}
});
}
};
I am trying to test it using jest with this:
const IDCheck = require(
'./IDCheck'
);
let errors = [
{
parentSchema: {
regexp: '/^((?!\\bMyId\\b).)*$/i'
}
}
];
describe('IDCheck', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('calls _recordError with IDCHECK', () => {
jest.spyOn(this, '_recordError');
IDCheck.idCheck(errors);
});
});
however, when running jest, I get
Cannot spy the _recordError property because it is not a function; undefined given instead
Is there a way of mocking, testing for _recordError() having been called, or not called and with the correct parameter, without passing _recordError through as a parameter?
A few things about this line: jest.spyOn(this, '_recordError');
this has to be IDCheck because there is no this in scope since you are using arrow functions that inherit this if previously set (which it isn't). You can console.log(this) right above the line to prove that point.
'_recordError' is not a method of IDCheck. spyOn checks the target's methods, not methods called within it. Now if _recordError is a method of IDCheck, then you should be ok.
Finally, you basically have to return the data you want in order to verify it. There's no real way to check what was passed unless you return it.
Here's a solution I came up with that does not include some fixes you'd have to implement to fix the potential workflow flaws.
const IDCheck = {
idCheck: function(errors) {
return errors.map(error => {
if (error.parentSchema.regexp === '/^((?!\\bMyId\\b).)*$/i') {
return this._recordError('IDCHECK')
}
})
},
_recordError: function(data) {
return data
}
}
let errors = [
{
parentSchema: {
regexp: '/^((?!\\bMyId\\b).)*$/i'
}
}
];
describe('IDCheck', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('calls _recordError with IDCHECK', () => {
const spy = jest.spyOn(IDCheck, '_recordError')
const check = IDCheck.idCheck(errors).includes('IDCHECK')
expect(spy).toHaveBeenCalled()
expect(check).toBe(true)
});
});

Resources