gpt4 book ai didi

unit-testing - 如何用 jest 和 enzyme 测试 websocket?

转载 作者:行者123 更新时间:2023-12-05 07:10:15 26 4
gpt4 key购买 nike

我正在构建一个网络应用程序并希望对其进行单元测试。它还有 Socket.io websocket 后端(expressjs 后端)和 socket.io 客户端在 react app 上,这是 create-react-app 应用程序。这是到目前为止的测试:

import React from 'react';

// 3rd party imports
import { render } from '@testing-library/react';
import { shallow, mount } from "enzyme";
import { SocketIO, Server } from 'mock-socket';

// custom imports
import App from '../App';
import Tasks from '../components/Tasks';

describe('App', () => {
let wrapper, shallowWrapper;
const mockServer = new Server('ws://localhost:8080');
window.io = SocketIO;
beforeEach(async () => {
wrapper = mount(<App />);
//start web socket config with mock-server
mockServer.on('connection', socket => {
socket.emit('task', 'test message from mock server');
});
// end web socket config
shallowWrapper = shallow(<App />);
});

it("renders", () => {
shallow(<App />);
});

test('renders right text', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/BI4 Monitor/i);
expect(linkElement).toBeInTheDocument();
});

it('has one unordered list', () =>{
expect(wrapper.find("ul")).toHaveLength(0);
});

it("displays initial empty list", () => {
expect(wrapper.find("li")).toHaveLength(0);
});

it("has Tasks component", () => {
console.log(shallowWrapper.debug())
expect(shallowWrapper.contains(<Tasks/>)).toBe(true);
});

});

我正在使用这个模拟库: https://github.com/thoov/mock-socket

这是 App.js

import React, { useEffect, useState } from 'react';

// 3rd party imports
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import { useImmer } from 'use-immer';
import _ from "underscore";

// custom imports
import { SocketUtil } from './utils';
import Tasks from './components/Tasks';

const socket = SocketUtil.init();

function App() {
const [msg, setMsg] = useState([]);
function handleData(payload) {
// data = [...data, payload]
setMsg(m => m.concat(payload));
}

useEffect(() => {
socket.on('task', payload => {
console.log("taskkkk")
handleData(payload);
});
});


return (
<Container>
<Row className="row">
<Col xs={12}>
<h1>BI4 Monitor</h1>
{/* <Tasks/> */}
{_.map(msg, function(m) {
return (
<p>{m.key}</p>
);
})}
<Tasks/>
</Col>
</Row>
</Container>
);
}

export default App;

我想打印 console.log("taskkkk")或者基本上只是单元测试以查看更多 <p>{m.key}</p>得到渲染但没有发生。我也试过 https://github.com/romgain/jest-websocket-mock但没有运气。有什么想法可以实现吗?

最佳答案

我只是尝试自己模拟 WebSocket JS API。请引用这里https://stackoverflow.com/a/68579278/4124267

关于unit-testing - 如何用 jest 和 enzyme 测试 websocket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61292587/

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