mercredi 1 avril 2020

Jest mock class instance of class and function in class

I have a class I'm testing, let's call it ToTest.ts, and it instantiates and instance of another class, Irrelevant.ts, and calls a method on it called doSomething.

// ToTest.ts
const irrelevant = new Irrelevant();
export default class ToTest {

  // ... some implementation, constructor, etc.

  public static callIrrelevant() {
    return irrelevant.doSomething();
  }
}

//Irrelevant.ts
export default class Irrelevant {

  // ... some implementation, constructor, etc.

  public doSomething() {
    console.log("doing something");
  }
}

How can I mock irrelevant.doSomething() in my jest test?

I've tried:

import Irrelevant from '../some/path/irrelevant';
test('irrelevant.doSomething is mocked' => {
  Irrelevant.prototype.doSomething = () => jest.fn().mockImplementation(() => {
    console.log(`function got called`)
  });
  const toTest = new ToTest();
  toTest.callIrrelevant();
});
test('irrelevant.doSomething is mocked -- second try' => {
  jest.mock('../some/path/irrelevant')
  const mockDoSomething = jest.spyOn(Irrelevant, "doSomething"); // Gives error: Argument of type '"doSomething"' is not assignable to parameter of type 'never'.
  findMock.mockImplementation(() => {
    console.log(`function got called`)
  });
  const toTest = new ToTest();
  toTest.callIrrelevant();
 });
});

The mock implementations don't get triggered in either test. How can I mock this correctly?

Aucun commentaire:

Enregistrer un commentaire