简体   繁体   中英

How to spyOn a function from the same module in jest?

Consider this set of code snippets where I want to write unit tests for function A , which internally calls function B during execution. Assume B is a set of API calls for validation that I want to mock return value to true.

But this spyOn method approach does not work, and the API calls in B still get executed. I've seen approaches with mocking the complete module with jest.requireActual() , but they do not seem to work too.

What could be a better way to test such functions without changing a lot in the codebase index.ts ?

 //index.ts async function A (a:string, b:string, c:string) { // code await B(data); // code } async function B (data:customType) { //code //API calls //code } export default { A, B }

 //index.test.ts import index from '../index.ts'; describe('Test suit', ()=>{ it('should be a test for function A', async ()=> { jest.spyOn(index, 'B').mockReturnValue(true); // code const result = await index.A('a','b','c'); // code }) })

There is not really a good way to do it, when the functions are in the same module with jest only.

But you can with Rewire , it's explained in this answer and worked very well in a similar situation for me: https://stackoverflow.com/a/52725067/16068019

Otherwise if it's an option you could move one of your functions to a different module, but that's not always an option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM