2

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.

10
  • What is expected result of functionIWantToTest() call? Commented Aug 13, 2017 at 18:56
  • Hey @guest271314 its in the test :), for anotherThing.do to have been called with a param. Commented Aug 13, 2017 at 19:07
  • Have not tried jest. What does jest.fn() return? Are there two different assignments of values to anotherThing.do? Note that no values are actually returned from functionIWantToTest() call Commented Aug 13, 2017 at 19:10
  • jest.fn() returns a mocked function, you can provide mock implementation by doing jest.fn(()=>{...} ). Yeah its a void function, I am expecting it do call something else(there is more logic in the real code) Commented Aug 13, 2017 at 19:13
  • Ok. Though still no value is returned from functionIWantToTest() call. Why do you anotherThing.do=jest.fn() if anotherThing is a function that is already defined at import anotherThing from 'anotherThing'? Commented Aug 13, 2017 at 19:15

1 Answer 1

1

Have not tried jest. You can use console.assert() to test the function calls and Promise values returned. Note, no value is actually returned from either of the function calls, if that matter to the expected result, see Why is value undefined at .then() chained to Promise?.

function functionIWantToTest() {
  return Promise.resolve({
      Id: 1
    })
    .then(data => {
      console.assert(data.Id === 1, data, [`${data.Id} is not equal to 1`]);
      console.assert(data.Id !== 1, data, [`${data.Id} is equal to 1`]);
    })
}

functionIWantToTest()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.