mardi 3 septembre 2019

Mock a specific class from a node module in jest

I would like to mock just the Socket class from the net node module (Docs).

I have a class that looks something like this...

import { Socket } from 'net';

class Foo {
    protected socket: Socket;

    constructor() {
        this.socket = new Socket();
    }

    connect() {
        const connPromise = new Promise<undefined>(resolve => {
            this.socket.connect(80, '192.168.1.1', () => {
                // Do some stuff with local state

                resolve();
            });
        });

        return connPromise;
    }
}

I am unsure how to mock the Socket class so I can provide the mock implementation for this.socket.connect.

import { Foo } from './foo';

// Can I just mock the Socket Class somehow?
jest.mock('net')

describe("Foo", () => {
    it('resolves on connect', () => {
        const tester = new Foo();

        expect(tester.connect()).resolves.toBeUndefined();
    })
})

How can I control the this.socket.connect method implementation?

Aucun commentaire:

Enregistrer un commentaire