gpt4 book ai didi

node.js - 用 Jest 模拟继承的类

转载 作者:行者123 更新时间:2023-12-03 11:49:26 25 4
gpt4 key购买 nike

我在延长 net.Socket .这样做时,我将按如下方式覆盖连接方法。

class ENIP extends Socket {
constructor() {
super();

this.state = {
session: { id: null, establishing: false, established: false },
error: { code: null, msg: null }
};
}

connect(IP_ADDR) {
const { registerSession } = encapsulation; //returns a buffer to send

this.state.session.establishing = true;

return new Promise(resolve => {
super.connect(EIP_PORT, IP_ADDR, () => { // This is what i want to mock -> super.connect
this.state.session.establishing = false;

this.write(registerSession());
resolve();
});
});
}
}

我要模拟底层 socket 类以便我可以模拟 super.connect .查看了 Facebook 的 docs在这件事上,我不确定如何继续为此类开发测试,因为所有方法都将扩展 super.someMethodToMock .有谁知道我应该采取的方法?如果我可以提供任何澄清细节,请告诉我。

最佳答案

您可以使用 jest.spyOn(object, methodName)Socket.prototype 上创建模拟方法.
例如。index.js :

import { Socket } from 'net';

const EIP_PORT = 3000;
const encapsulation = {
registerSession() {
return 'session';
},
};

export class ENIP extends Socket {
constructor() {
super();
this.state = {
session: { id: null, establishing: false, established: false },
error: { code: null, msg: null },
};
}

connect(IP_ADDR) {
const { registerSession } = encapsulation;
this.state.session.establishing = true;

return new Promise((resolve) => {
super.connect(EIP_PORT, IP_ADDR, () => {
this.state.session.establishing = false;
this.write(registerSession());
resolve();
});
});
}
}
index.test.js :
import { ENIP } from './';
import { Socket } from 'net';

describe('ENIP', () => {
afterAll(() => {
jest.restoreAllMocks();
});
describe('#connect', () => {
it('should pass', async () => {
const writeSpy = jest.spyOn(Socket.prototype, 'write').mockImplementation();
const connectSpy = jest.spyOn(Socket.prototype, 'connect').mockImplementationOnce((port, addr, callback) => {
callback();
});
const enip = new ENIP();
await enip.connect('localhost');
expect(writeSpy).toBeCalledWith('session');
expect(connectSpy).toBeCalledWith(3000, 'localhost', expect.any(Function));
});
});
});
带有覆盖率报告的单元测试结果:
 PASS  src/stackoverflow/48888509/index.test.jsx (10.43s)
ENIP
#connect
✓ should pass (7ms)

-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.jsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.357s
源代码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/48888509

关于node.js - 用 Jest 模拟继承的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com