嘲笑节点模块中的特定类

时间:2019-09-03 13:16:04

标签: javascript typescript testing jestjs

我只想模拟Socket节点模块(Docs)中的net类。

我有一堂课,看起来像这样...

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;
    }
}

我不确定如何模拟Socket类,因此可以为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();
    })
})

如何控制this.socket.connect方法的实现?

1 个答案:

答案 0 :(得分:0)

尝试为模拟函数提供factory

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

(编辑,因为我忘记了您不能从玩笑工厂的外部范围中引用函数:D)