yalpsid eman
yalpsid eman

Reputation: 3432

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 an 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?

Upvotes: 2

Views: 9233

Answers (2)

JeromeBu
JeromeBu

Reputation: 1159

You have to consider mockImplementation as the mock of the constructor of Irrelevant. What it will return will be your mock. So you can do like that :

import Irrelevant from '../some/path/irrelevant';

jest.mock('../some/path/irrelevant')

const spyDoSomething = jest.fn();

(Irrelevant as any).mockImplementation(() => {
  return { doSomething: spyDoSomething };
})

Upvotes: 4

yalpsid eman
yalpsid eman

Reputation: 3432

import Irrelevant from '../some/path/irrelevant';
test('irrelevant.doSomething is mocked' => {
  Irrelevant.prototype.doSomething = () => jest.fn(() => {
    console.log(`function got called`)
  });
  const toTest = new ToTest();
  toTest.callIrrelevant();
});

Upvotes: 1

Related Questions