gpt4 book ai didi

javascript - 如何在定义为箭头函数(类属性)的 React 组件上测试组件方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:39:55 39 4
gpt4 key购买 nike

通过使用 spy 和 Component.prototype,我能够很好地测试类方法。但是,我的许多类方法都是类属性,因为我需要使用 this(用于 this.setState 等),而且在构造函数中绑定(bind)非常繁琐且看起来很难看,我认为使用箭头函数要好得多。我使用类属性构建的组件在浏览器中工作,所以我知道我的 babel 配置是正确的。下面是我要测试的组件:

    //Chat.js
import React from 'react';
import { connect } from 'react-redux';

import { fetchThreadById, passMessageToRedux } from '../actions/social';
import withLogin from './hoc/withLogin';
import withTargetUser from './hoc/withTargetUser';
import withSocket from './hoc/withSocket';
import ChatMessagesList from './ChatMessagesList';
import ChatForm from './ChatForm';

export class Chat extends React.Component {
state = {
messages : [],
};
componentDidMount() {
const { auth, targetUser, fetchThreadById, passMessageToRedux } = this.props;
const threadId = this.sortIds(auth._id, targetUser._id);
//Using the exact same naming scheme for the socket.io rooms as the client-side threads here
const roomId = threadId;
fetchThreadById(threadId);
const socket = this.props.socket;
socket.on('connect', () => {
console.log(socket.id);
socket.emit('join room', roomId);
});
socket.on('chat message', message => passMessageToRedux(message));
//socket.on('chat message', message => {
// console.log(message);
// this.setState(prevState => ({ messages: [ ...prevState.messages, message ] }));
//});
}

sortIds = (a, b) => (a < b ? `${a}_${b}` : `${b}_${a}`);

render() {
const { messages, targetUser } = this.props;
return (
<div className='chat'>
<h1>Du snakker med {targetUser.social.chatName || targetUser.info.displayName}</h1>
<ChatMessagesList messages={messages} />
<ChatForm socket={this.props.socket} />
</div>
);
}
}
const mapStateToProps = ({ chat: { messages } }) => ({ messages });

const mapDispatchToProps = dispatch => ({
fetchThreadById : id => dispatch(fetchThreadById(id)),
passMessageToRedux : message => dispatch(passMessageToRedux(message)),
});

export default withLogin(
withTargetUser(withSocket(connect(mapStateToProps, mapDispatchToProps)(Chat))),
);

Chat.defaultProps = {
messages : [],
};

这是测试文件:

//Chat.test.js
import React from 'react';
import { shallow } from 'enzyme';
import { Server, SocketIO } from 'mock-socket';

import { Chat } from '../Chat';
import users from '../../fixtures/users';
import chatMessages from '../../fixtures/messages';

let props,
auth,
targetUser,
fetchThreadById,
passMessageToRedux,
socket,
messages,
wrapper,
mockServer,
spy;

beforeEach(() => {
window.io = SocketIO;
mockServer = new Server('http://localhost:5000');
mockServer.on('connection', server => {
mockServer.emit('chat message', chatMessages[0]);
});
auth = users[0];
messages = [ chatMessages[0], chatMessages[1] ];
targetUser = users[1];
fetchThreadById = jest.fn();
passMessageToRedux = jest.fn();
socket = new io('http://localhost:5000');
props = {
mockServer,
auth,
messages,
targetUser,
fetchThreadById,
passMessageToRedux,
socket,
};
});

afterEach(() => {
mockServer.close();
jest.clearAllMocks();
});

test('Chat renders correctly', () => {
const wrapper = shallow(<Chat {...props} />);
expect(wrapper).toMatchSnapshot();
});

test('Chat calls fetchThreadById in componentDidMount', () => {
const wrapper = shallow(<Chat {...props} />);
const getThreadId = (a, b) => (a > b ? `${b}_${a}` : `${a}_${b}`);
const threadId = getThreadId(auth._id, targetUser._id);
expect(fetchThreadById).toHaveBeenLastCalledWith(threadId);
});

test('Chat calls componentDidMount', () => {
spy = jest.spyOn(Chat.prototype, 'componentDidMount');
const wrapper = shallow(<Chat {...props} />);
expect(spy).toHaveBeenCalled();
});

test('sortIds correctly sorts ids and returns threadId', () => {
spy = jest.spyOn(Chat.prototype, 'sortIds');
const wrapper = shallow(<Chat {...props} />);
expect(spy).toHaveBeenCalled();
});

倒数第二个测试检查 componentDidMount(不是类方法)是否被调用且没有错误运行,除了最后一个测试之外的所有其他测试也是如此。对于最后一个测试,Jest 给我以下错误:

FAIL  src\components\tests\Chat.test.js
● sortIds correctly sorts ids and returns threadId

Cannot spy the sortIds property because it is not a function; undefined given instead

65 |
66 | test('sortIds correctly sorts ids and returns threadId', () => {
> 67 | spy = jest.spyOn(Chat.prototype, 'sortIds');
68 | const wrapper = shallow(<Chat {...props} />);
69 | expect(spy).toHaveBeenCalled();
70 | });

at ModuleMockerClass.spyOn (node_modules/jest-mock/build/index.js:699:15)
at Object.<anonymous> (src/components/tests/Chat.test.js:67:16)

有人告诉我可以使用 mount 来自 enzyme 而不是 shallow 然后使用 Chat.instance 而不是 Chat .prototype,但据我了解,如果我这样做, enzyme 也会呈现 Chat 的子级,我当然不希望那样。我实际上尝试过使用 mount,但随后 Jest 开始提示 connect(ChatForm) 在其上下文或 Prop 中没有 store ( ChatForm 连接到 redux,但我喜欢通过导入非连接组件和模拟 redux 存储来测试我的 redux 连接组件)。有谁知道如何使用 Jest 和 Enzyme 测试 React 组件的类属性?提前致谢!

最佳答案

即使渲染很浅,也可以调用wrapper.instance()方法。

it("should call sort ids", () => {
const wrapper = shallow(<Chat />);
wrapper.instance().sortIds = jest.fn();
wrapper.update(); // Force re-rendering
wrapper.instance().componentDidMount();
expect(wrapper.instance().sortIds).toBeCalled();
});

关于javascript - 如何在定义为箭头函数(类属性)的 React 组件上测试组件方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49582918/

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