If I have code something like this:
import externalThing from 'externalThing'
import anotherThing from 'anotherThing'
function functionIWantToTest()
{
externalThing.doSomething()
.then(data=>{
anotherThing.do(data.Id)
})
}
What is the best practice way to unit test this?
Ideally the test would be something like this:
import externalThing from 'externalThing'
import anotherThing from 'anotherThing'
jest.mock('externalThing',()=>jest.fn())
jest.mock('anotherThing',()=>jest.fn())
describe('when calling functionIWantToTest',()=>{
beforeEach(()=>{
anotherThing.do=jest.fn()
//mock external thing somehow so that it still the 'then' code
functionIWantToTest()
})
it('anotherThing should be called',()=>{
expect(anotherThing.do).toHaveBeenCalledWith(1)
});
});
But when I try I just end up building a chain of mocked functions with jest.fn() and no code actually gets executed.
functionIWantToTest()call?anotherThing.doto have been called with a param.jest. What doesjest.fn()return? Are there two different assignments of values toanotherThing.do? Note that no values are actually returned fromfunctionIWantToTest()calljest.fn()returns a mocked function, you can provide mock implementation by doingjest.fn(()=>{...} ). Yeah its a void function, I am expecting it do call something else(there is more logic in the real code)functionIWantToTest()call. Why do youanotherThing.do=jest.fn()ifanotherThingis a function that is already defined atimport anotherThing from 'anotherThing'?