7

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

2 Answers 2

5

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()
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, "const mockMyFunc = MyClass.mock.instances[0].myFunc" top solution!
0

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

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.