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

5

我可以通过使用间谍和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 : [],
    };

这里是测试文件:

//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)

我被告知可以使用Enzyme中的mount代替shallow,然后使用Chat.instance代替Chat.prototype。但据我了解,如果这样做,Enzyme还会渲染Chat的子元素,而我肯定不想要这个结果。我确实尝试过使用mount,但是Jest开始抱怨connect(ChatForm)在其上下文或props中没有storeChatForm连接到redux,但我喜欢通过导入非连接组件并模拟redux store来测试我的redux-connected组件)。有谁知道如何使用Jest和Enzyme测试React组件的类属性?先谢谢大家!

我不确定为什么你在sortIds中使用属性初始化器语法,因为它没有使用this。另外,你测试的方面是什么?是componentDidMount是否调用了该方法,还是它对其输入计算出了有效结果?根据你的测试描述,似乎是后者,在这种情况下,可以将其与实例化的类隔离开来进行测试。 - Dave Meehan
你说得完全正确,它没有使用 this!它曾经使用过 this,但是我的测试不起作用,调试期间我将其从中删除了,但现在我会把它放回去的 :). 感谢您的评论,但我已经澄清了一切,现在一切都正常工作。祝您有愉快的一天! - Christoffer Corfield Aakre
1个回答

11
即使渲染是浅层次的,您仍然可以调用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();
 });

1
谢谢!这正是我在寻找的!我会接受你的答案。 - Christoffer Corfield Aakre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接