0

Lets say I have this code below and I want to test someFunc() but I want to mock the doSomething() function? How can I do it in a test when the SomeClass is initialized only inside the someFunc() itself and not in the test?

class SomeClass {
  constructor(element){
    this.element = element
  }
  
  doSomething(element){
    ...
  }
}

function someFunc() {
  const newClass = new SomeClass()
  newClass.doSomething() // I want this to get to the mocked function
}

I am using jest, please help!

2 Answers2

0

Try some testing frameworks, most of them provide spies which allow you to mock specific functions for given classes.

For example, you can try Jasmine - https://jasmine.github.io/api/edge/Spy.html Where you would do something like

spyOn(newClass, 'doSomething').and.returnValue(42);
  • But the newClass is not initialized in the test. Will it still work? – Danielle Vardi Mar 22 '22 at 13:58
  • @DanielleVardi then I would maybe consider mocking your named function completely, something like this https://stackoverflow.com/questions/39755439/how-to-mock-imported-named-function-in-jest-when-module-is-unmocked – Pavel Pazderník Mar 22 '22 at 14:01
0

There are multiple ways to mock es6 class in Jest: https://jestjs.io/docs/es6-class-mocks

hulufei
  • 737
  • 1
  • 6
  • 17