Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test class instance inside a function with Jest

Tags:

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

like image 546
Metarat Avatar asked May 16 '18 22:05

Metarat


1 Answers

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()
})
like image 97
butchyyyy Avatar answered Sep 28 '22 17:09

butchyyyy