我只想模拟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
方法的实现?
答案 0 :(得分:0)
尝试为模拟函数提供factory:
jest.mock('net', () => ({
Socket: function() {
return {
connect() {
return 'Hello World'
}
}
}
}))
(编辑,因为我忘记了您不能从玩笑工厂的外部范围中引用函数:D)