问题
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