How to test class instance inside a function with Jest

11,813

One of the option is to replace MyClass module with mock implementation

const mockmyfunc = jest.fn()
jest.mock("path/to/external/package/MyClass", () => {
  return jest.fn().mockImplementation(() => {
    return {myfunc: mockmyfunc}
  })
})

And then write following test

it("Test myfunc called in functionToBeTested", () => {
  functionToBeTested()
  expect(mockmyfunc).toHaveBeenCalled()
})

Note that this is not the only way, you can dive into https://facebook.github.io/jest/docs/en/es6-class-mocks.html for other alternatives.

Update

If the myfunc would be an actual function (which i guess is not an option since it's external package?)

export class MyClass {
    myFunc() {
      // do smth
    }
}

and you would not need to replace the implementation, you could be using jest's automock

import MyClass from "path/to/external/package/MyClass"
jest.mock("path/to/external/package/MyClass")

it("Test myfunc called in functionToBeTested", () => {
  functionToBeTested()
  const mockMyFunc = MyClass.mock.instances[0].myFunc
  expect(mockMyFunc).toHaveBeenCalled()
})
Share:
11,813
Metarat
Author by

Metarat

Updated on June 12, 2022

Comments

  • Metarat
    Metarat almost 2 years

    I have the following hypothetical scenario:

    // file MyClass.js in an external package
    class MyClass {
        myfunc = () => {
            // do something
        }
    }
    
    // file in my project
    function myFunctionToBeTested() {
        const instance = new MyClass()
        instance.myFunc()
    }
    

    I need to create a test with Jest that makes sure instance.myFunc was called

  • Stefano Spkg Gagliardi
    Stefano Spkg Gagliardi over 3 years
    Thanks, "const mockMyFunc = MyClass.mock.instances[0].myFunc" top solution!