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

Javascript 如何在定义为箭头函数(类属性)的React组件上测试组件方法?,javascript,reactjs,jestjs,enzyme,class-method,Javascript,Reactjs,Jestjs,Enzyme,Class Method,通过使用spies和Component.prototype,我可以很好地测试类方法。但是,我的许多类方法都是类属性,因为我需要使用this(对于this.setState,等等),而且由于构造函数中的绑定非常繁琐,看起来很难看,因此我认为使用箭头函数更好。我使用类属性构建的组件在浏览器中工作,因此我知道我的babel配置是正确的。下面是我尝试测试的组件: //Chat.js import React from 'react'; import { connect } fro

通过使用spies和
Component.prototype
,我可以很好地测试类方法。但是,我的许多类方法都是类属性,因为我需要使用
this
(对于
this.setState
,等等),而且由于构造函数中的绑定非常繁琐,看起来很难看,因此我认为使用箭头函数更好。我使用类属性构建的组件在浏览器中工作,因此我知道我的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 : [],
    };

有人告诉我,我可以从Ezyme中使用
mount
而不是
shall
,然后使用
Chat.instance
而不是
Chat.prototype
,但据我所知,如果我这样做,Ezyme也会渲染
Chat
的孩子,我当然不希望这样。实际上,我尝试过使用
mount
,但后来Jest开始抱怨
connect(ChatForm)
在其上下文或道具中没有
store
ChatForm
连接到redux,但我喜欢通过导入未连接的组件并模拟redux存储来测试我的redux连接组件)。有人知道如何用Jest和Ezyme测试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();
 });
it(“应该调用排序ID”,()=>{
常量包装器=浅();
wrapper.instance().sortIds=jest.fn();
wrapper.update();//强制重新呈现
wrapper.instance().componentDidMount();
expect(wrapper.instance().sortIds).toBeCalled();
});

谢谢!这正是我要找的!我将接受您的回答。我不确定您为什么要使用
sortIds
的属性初始值设定项语法,而它不使用
。另外,您测试的是哪个方面,即
componentDidMount
调用了该方法,还是它为其输入计算了有效的结果?在您的测试描述中似乎是后一种情况,在这种情况下,它可以独立于被实例化的类进行测试。您完全正确,它没有使用
这个
!它确实使用了这个,但后来我的测试不起作用,在调试期间,我从中删除了
this
,但现在我要把它放回去:)。谢谢你的评论,但我现在已经把一切都清理干净了,一切正常。祝您有个美好的一天!
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)
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();
 });