admin管理员组

文章数量:1290959

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

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

Share Improve this question asked May 16, 2018 at 22:21 MetaratMetarat 6392 gold badges9 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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()
})

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

本文标签: javascriptHow to test class instance inside a function with JestStack Overflow