Mocking local module with isolateModules - jestjs

I'm using react-easy-state and I want to reset the store on each test. Which works fine. But when I try to mock a local module the mocked function does not get called. The mocking works fine without the use of isolateModules.
How do I do mocking on a module in conjunction with isolateModules?
This is what I'm trying to do:
beforeEach(() => {
jest.doMock('./util/getValidPosition', () => {
return { getValidPosition: jest.fn() };
});
jest.isolateModules(() => {
store = require('./store').workspace;
});
});
afterEach(() => {
jest.resetModules();
});

Related

Spying a call made to a method of a dependency in NodeJs (Chai)

I have an application where I have a Controller called NotesController and a service injected in it called NotesService which I use to retrieve notes.
I am trying to write a unit test for my Controller using spies from Chai library:
chai.use(spies);
describe('Notes Controller', () => {
chai.spy.on(notesController, 'notesService.get', (id) => id);
}
describe('Get note by id', () => {
it('Retrieves note successfully', (done) => {
notesController.get("1")
.then(() => {
chai.expect('notesService.get').to.have.been.called();
})
.catch((error: any) => {
done(error)
});
}
}
My test fails because for some reason it tries to run that method notesService.get, so it fails when it tries to connect to the DB.
How can I mock this method call (notesService.get) using spies instead of actually running it?

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.

Mocking Playwright library

Working on a project using the new playwright library.
I've started writing some unit tests and want to mock out portions of the library as I test.
Right now I'm getting the error Cannot Read Property 'launch' of undefined.
import MyModule from './myModule';
import { firefox } from 'playwright'
function bootStrapComponent() {
return new MyModule();
};
describe('myModule Class', () => {
var myModule;
describe('main', () => {
beforeEach(() => {
myModule = bootStrapComponent();
})
it('should mock browswer', async() => {
let browser = jasmine.createSpyObj('firefox', ['launch']);
myModule.firefox.launch({});
expect(browser.launch).toHaveBeenCalled();
});
});
I'm not sure I'm even doing this correctly. Can you point me in the right direction?

Nodejs Jest mocking is not working in multiple describe block in a single file, it works in first describe block only

I am using jest for unit testing in my node express application,please excuse , because i am new to all this
in my abc.test.js
const s3Helper = require('../../../../../lib/s3_helper');
beforeEach(async () => {
s3Helper.uploadBufferToS3 = jest.fn(() => true);
});
describe('test1', () => {
it('test1', async () => {
expect(s3Helper.uploadBufferToS3)
.toHaveBeenCalled();
});
});
describe('test2', () => {
it('test2', async () => {
expect(s3Helper.uploadBufferToS3)
.toHaveBeenCalled();
});
});
so when i run this test file in test1 it returns that test is passed, however in test2 it returns expected >=1 returned 0.
since i am mocking it beforeEach i expect it should return 1 for each describe block

Resources