Metarat
Metarat

Reputation: 639

How to test class instance inside a function with Jest

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

Upvotes: 7

Views: 16471

Answers (2)

butchyyyy
butchyyyy

Reputation: 355

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()
})

Upvotes: 5

immertreu
immertreu

Reputation: 41

you can mock out the class and assign the default export of that file to a variable as follows:

jest.mock('../../utils/api/api');
const FakeClass = require('../someFile.js').default;

then access calls to a function on your mock class like this:

FakeClass.prototype.myFunc.mock.calls

Upvotes: 0

Related Questions