嘲笑节点模块中的特定类 [英] Mock a specific class from a node module in jest
本文介绍了嘲笑节点模块中的特定类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想模拟net
节点模块中的Socket
类(文档).
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;
}
}
我不确定如何模拟Socket类,因此可以为this.socket.connect
提供模拟实现.
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();
})
})
如何控制this.socket.connect
方法的实现?
推荐答案
尝试提供(编辑,因为我忘记了您不能从玩笑工厂的外部范围中引用函数:D)
(Edited because I forgot you could not reference functions from the outer scope within a jest factory :D)
这篇关于嘲笑节点模块中的特定类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文