Using Jest to test a class with dependencies

Viewed 22

I have the following method I want to test:

export const Update = (factory: Factory, service: MyService) => {
  return async (input: Input) => {
    return factory.transaction(async (fact) => {
      const someValues = myService.getSomeValues()
      return fact.findAll(someValues, input)
    }
  }
}

So in order to test this, I need to call this method and pass in a mocked factory (which is a class), how do I go about doing this? Do I also need to mock the factory's transaction method?

The point of the test is to make sure that I get back all the records, so I also need to mock the return of the repository and the findAll method, how do I go about doing this?

I thought I would just be able to mock the module the class is from and then pass that in but it's not working as I expected, how do I ensure that the inner code gets called?

Minimal reproducible example:

import Factory from 'factory'
jest.mock('factory')
const mockedFactory = jest.mocked(Factory)
const expectedUpdate = Update(mockedFactory)

I thought I would then be able to put mockedFactory into the call to Update but instead I get this error:

Argument of type 'MockedObject' is not assignable to parameter of type 'Factory'. Type 'MockInstance<Factory, [sequelize: Sequelize]> & {} & { prototype: Factory; }' is missing the following properties from type 'Factory': sequelize, transaction

What do I need to do to get rid of this error and then ensure that the transaction method from this class is called?

I then need to ensure that myService is called so I also need to mock this, I assume in a similar way. But again repeating the above I get the same error that the types don't match.

I then want to ensure that when fact.findAll is called with the correct parameters (which I will be able to control as I can control what myService.getSomeValues returns, assuming I can get it to work) and that the method Update overall returns what I expect it to and then I can test that that is what I expect.

0 Answers
Related