Home > Software engineering >  How to mock external class in another initialized in another class?
How to mock external class in another initialized in another class?

Time:09-29

I have following files and classes

//A.ts 

export abstract class A{
    
    protected abstract method1(arg){
        
    }
}

// Session.ts
export class Session{
    constructor(socket: WebSocket){
         this._socket = socket;
         this._socket.on('close', () => {do something} );
         this._socket.on('error', () => {do something} );
         this._socket.on('message', () => {do something} );
    }
    setSomeSocket(someSocket: WebSocket){
         this._anotherSocket = someSocket;
         this._anotherSocket.on('close', () => {do something} );
         this._anotherSocket.on('error', () => {do something} );
    };
}


// B.ts
    export class B extends A{
       
        protected async method1(arg){
            try{
                let tempSession = new Session();
                tempSession.setSomeSocket(socket);
                // do something with temp
            }
            catch(exception){
                
            }
        }
    }


// B.spec.ts
describe("B test", () => {
    it("some test", () => {
        const varB = new B();
        
        await varB["method1"](arg);
        expect(spied).toBeCalledTimes(1);
    });
})

I want to mock the class Session so that it doesn't create any problem in socket.on() methods. I am sending mocked websockets. The class is external and I want the mock implementation inside test file such that when running the test, the mocked class gets called inside B.ts

CodePudding user response:

You can mock directly with the jest:

jest.mock('./Session');

beforeEach(() => {
    Session.mockClear();
})

Check out the manual mocking and auto mocking from Jest documentation.

CodePudding user response:

As stated in another comment you can mock Session with jest

const mockSetSameSocks = jest.fn(); // note name starts with mock, important
jest.mock('./Session', () => {
  return {
    Session: jest.fn(() => ({
      setSameSocks: mockSetSameSocks,
    }))
  }
});

// B.spec.ts
describe("B test", () => {
  beforeEach(() => {
    mockSetSameSocks.mockClear();
  })

  it("some test", () => {
    const varB = new B();
        
    await varB["method1"](arg);
    expect(mockSetSameSocks).toBeCalledTimes(1);
  });
})

  • Related