Mock a specific class from a node module in jest

做~自己de王妃 提交于 2021-01-29 02:06:07

问题


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?


回答1:


Try providing a factory to the mock function:

jest.mock('net', () => ({
    Socket: function() {
        return {
            connect() {
                return 'Hello World'
            }
        }
    }
}))

(Edited because I forgot you could not reference functions from the outer scope within a jest factory :D)



来源:https://stackoverflow.com/questions/57772569/mock-a-specific-class-from-a-node-module-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!