我正在构建一个Webapp,并希望对其进行单元测试。它在具有create-react-app应用程序的react应用程序上还具有Socket.io websocket后端(expressjs后端)和socket.io客户端。 到目前为止,这是测试:
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
,但是没有运气。
有什么想法可以实现吗?