Priti Biyani
Priti Biyani

Reputation: 424

How to stub a class method inside a function under test using sinon?

   //Some utility 
   import SomeClass from 'someclass';

   const LoadService = {

     getData(){
     const someClassInstance = new SomeClass('param1', 'param2');
     return someClassInstance.load('param33')
     },

   };

  module.exports =LoadService;

The intend is to test LoadService by mocking SomeClass as SomeClass is already tested. I'm using sinon 2.1.0.

I want to check getData method of LoadService. Is it possible to mock load class method of SomeClass.

Any help is appreciated.

Upvotes: 0

Views: 593

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 110892

First you have to mock the someClass module so it will return a jest spy and import this module into your test.

import SomeClass from 'someClass'
jest.mock('someclass', ()=>jest.fn())

then you need to create the spy for the load function and for the module itself.

const load = jest.fn()
SomeClass.mockImplementation(jest.fn(()=>({load})))

after calling the LoadService you can check that the module itself and the load function were called

expect(someClassMock).toHaveBeenCalledWith('param1', 'param2')
expect(load).toHaveBeenCalledWith('param33')

So after all there is no need to use Sinon everything can be done using Jest

Upvotes: 1

Related Questions