如何使用jest for componentDidmount和componetdidupdate编写单元测试用例?

时间:2018-05-27 16:04:26

标签: reactjs unit-testing sinon jest

我是使用反应组件的jest进行单元测试的新手。如何为组件生命周期编写单元测试。我试过但它没有成功。我的意思是它实际上没有涵盖完整的组件。当我尝试使用npm run test时,它显示id proptype expect string的错误。请帮帮我。

My component:

    import $ from 'jquery';
    import React from 'react';
    import { Scrollbars } from 'react-custom-scrollbars';
    import WatsonMessageBox from './watsonmessagebox';
    import StudentMessageBox from './studentmessagebox';
    import ErrorMessageBox from './errormessagebox';

    class Chatlist extends React.Component {
      componentDidMount() {
        document.getElementsByClassName('scrollDM')[0].firstChild.tabIndex = -1;
      }
      componentDidUpdate() {
        const node = $('.scrollDM').children().last();
        node.css('border-radius', '6px');
        node.css('width', '11px');
        node.children(0).css('background-color', '#c4c4c4');
        // eslint-disable-next-line
        const { scrollbars } = this.refs;
        if (this.props.updateComponent) {
          scrollbars.scrollToBottom();
        }
      }

      render() {
        // // console.log('chatlist props== ', this.props);
        return (<Scrollbars
        // eslint-disable-next-line
          ref={'scrollbars'} className="scrollDM msg-blck chat-block"
        >
          <div className="alignBottom body-height">
            {
            this.props.messages.map((arg, index) => {
              let isLOEO = false;
              switch (arg.senderId) {
                case 'watson':
                case 'ack':
                  if (arg.chatLabel && (typeof arg.chatLabel === 'object')) {
                    isLOEO = arg.chatLabel.type === 'QUESTION';
                  } else {
                    isLOEO = false;
                  }
                  return (<WatsonMessageBox
                    id={index} message={arg.chatText} isLOEO={isLOEO}
                    label={arg.chatLabel} index={index + 10}
                    showBar={this.props.messages.length - 1 > index}
                  />);
                case 'err':
                  return <ErrorMessageBox id={index} message={arg.chatText} index={index + 10} />;
                case 'student':
                default:
                  return (<StudentMessageBox
                    id={index} key={index} isError={arg.isRetry}
                    retryAction={this.props.retryAction} retryMessage={this.props.retryMessage}
                    message={arg.chatText} label={arg.chatLabel} index={index + 10}
                  />);
              }
            })
          }
          </div>
        </Scrollbars>
        );
      }

    }

    Chatlist.propTypes = {
      updateComponent: React.PropTypes.bool,
      messages: React.PropTypes.array,
      retryMessage: React.PropTypes.string,
      retryAction: React.PropTypes.function
    };

    Chatlist.defaultProps = {
      messages: []
    };
    export default Chatlist;

My unit test using jest looks like as: 
    import React from 'react';
import Chatlist from '../components/dialogManager/chatlist';
import WatsonMessageBox from '../components/dialogManager/watsonmessagebox';
import ErrorMessageBox from '../components/dialogManager/errormessagebox';
import StudentMessageBox from '../components/dialogManager/studentmessagebox';
import { shallow, mount } from 'enzyme';
import renderer from 'react-test-renderer';

describe('Chatlist', () => {
  let component;
  const mockFn = jest.fn();
  const mockOutputObj = [{
    type: 'DEFAULT',
    text: 'Research that relies on statistical analysis of numerical or categorical data.  I hope that helps.'
  }, {
    type: 'DEFAULT',
    text: 'Let\'s go back to my question:'
  }, {
    type: 'QUESTION',
    text: 'What is the relationship between dependent and independent variables?'
  }, {
    type: 'MENU_ITEM',
    text: 'what is quantitative research?',
    return_value: 'what is quantitative research?'
  }, {
    type: 'MENU_ITEM',
    text: 'what is mixed method research?',
    return_value: 'what is mixed method research?'
  }, {
    type: 'MENU_ITEM',
    text: 'what is qualitative research?',
    return_value: 'what is qualitative research?'
  }, {
    type: 'MENU_ITEM',
    text: 'I had a different question',
    return_value: 'I had a different question'
  }, {
    type: 'MENU_ITEM',
    text: 'That was actually my answer',
    return_value: 'That was actually my answer'
  }];
  const mockMessages = [{
    senderId: 'watson',
    chatLabel: {
      message: 'What conclusions can you draw about the physical changes and health concerns that occur during middle adulthood?',
      type: 'QUESTION'
    },
    Feedback: 'Feedback',
    autoConnectingMsg: 'Connection lost. Reconnecting',
    btnDone: 'Close',
    btnSubmit: 'Send',
    charRemaining: 'characters remaining',
    close: 'close',
    loading: 'Loading ...',
    longMsgError: 'Your message is too long.',
    manualConnectingMsg: 'Reconnecting',
    reconnectFailedMessage: 'Unable to reconnect. Please try again later.  ',
    retryButton: 'Retry',
    retryMessage: 'Message not sent. Click to retry.',
    textboxPlaceholder: 'Type a message...',
    unSupportedChar: 'Your message contains unsupported characters.',
    retryAction: mockFn
  }];

  const mockStudentMessages = [{
    senderId: 'student',
    outputObj: mockOutputObj,
    Feedback: 'Feedback',
    autoConnectingMsg: 'Connection lost. Reconnecting',
    btnDone: 'Close',
    btnSubmit: 'Send',
    charRemaining: 'characters remaining',
    close: 'close',
    loading: 'Loading ...',
    longMsgError: 'Your message is too long.',
    manualConnectingMsg: 'Reconnecting',
    reconnectFailedMessage: 'Unable to reconnect. Please try again later.  ',
    retryButton: 'Retry',
    retryMessage: 'Message not sent. Click to retry.',
    textboxPlaceholder: 'Type a message...',
    unSupportedChar: 'Your message contains unsupported characters.'
  }];

  const mockAckMessages = [{
    senderId: 'ack',
    outputObj: mockOutputObj,
    Feedback: 'Feedback',
    autoConnectingMsg: 'Connection lost. Reconnecting',
    btnDone: 'Close',
    btnSubmit: 'Send',
    charRemaining: 'characters remaining',
    close: 'close',
    loading: 'Loading ...',
    longMsgError: 'Your message is too long.',
    manualConnectingMsg: 'Reconnecting',
    reconnectFailedMessage: 'Unable to reconnect. Please try again later.  ',
    retryButton: 'Retry',
    retryMessage: 'Message not sent. Click to retry.',
    textboxPlaceholder: 'Type a message...',
    unSupportedChar: 'Your message contains unsupported characters.'
  }];

  const mockErrMessages = [{
    senderId: 'err',
    outputObj: mockOutputObj,
    Feedback: 'Feedback',
    autoConnectingMsg: 'Connection lost. Reconnecting',
    btnDone: 'Close',
    btnSubmit: 'Send',
    charRemaining: 'characters remaining',
    close: 'close',
    loading: 'Loading ...',
    longMsgError: 'Your message is too long.',
    manualConnectingMsg: 'Reconnecting',
    reconnectFailedMessage: 'Unable to reconnect. Please try again later.  ',
    retryButton: 'Retry',
    retryMessage: 'Message not sent. Click to retry.',
    textboxPlaceholder: 'Type a message...',
    unSupportedChar: 'Your message contains unsupported characters.'
  }];
  let spy;
  // afterEach(() => {
  //   spy.mockClear();
  // });
  // test('Should initialize the chatlist content', () => {
  //   // console.log('Chatlist component content== ', component);
  //   const tree = component.toJSON();
  //   // console.log('Chatlist tree== ', tree);
  //   expect(tree).toMatchSnapshot();
  // });
  test('Should render a chatlist messages', () => {
    component = shallow(<Chatlist
      messages={mockMessages}
      retryAction={mockFn}
      retryMessage={mockMessages.retryMessage}
      updateComponent={false}
    />);
    // // console.log('Chatlist component scrolldm child == ', component.find('.scrollDM').children().last());
    // // console.log('Chatlist component scrolldm [0].firstChild.tabIndex == ', component.find('.scrollDM').find('div').instance().props);
    // // console.log('Chatlist component instance== ', component.instance());
    // // console.log('Chatlist component== ', component.instance().props.messages.outputObj);
    expect(component.instance().props.messages).toEqual(mockMessages);
    expect(component.instance().props.retryAction).toEqual(mockFn);
    expect(component.instance().props.retryMessage).toEqual(mockMessages.retryMessage);
    expect(component.find('.scrollDM')).toHaveLength(1);
    expect(component.instance().props.updateComponent).toBeFalse();
    // expect(component.find('.scrollDM').prop('style')).to.deep.equal({ borderRadius: '6px' });
  });

  test('Should check a chatlist before mount', () => {
    component = shallow(<Chatlist
      messages={mockMessages}
      retryAction={mockFn}
      retryMessage={mockMessages.retryMessage}
      updateComponent={false}
    />);
    // console.log('Chatlist component prototype == ', component.prototype);
    spy = jest.spyOn(component.prototype, 'componentDidMount');
    const wrapper = mount(<Chatlist />);
    wrapper.instance().componentDidMount();
    expect(spy).toHaveBeenCalled();
    // expect(component.find('.scrollDM').prop('style')).to.deep.equal({ borderRadius: '6px' });
  });

  test('Should check the senderId be watson in chatlist component', () => {
    component = shallow(<Chatlist
      messages={mockMessages}
      retryAction={mockFn}
      retryMessage={mockMessages.retryMessage}
      updateComponent={false}
    />);
    component.instance().props.messages.map((arg, index) => {
      [
      { senderId: 'watson', components: <WatsonMessageBox id={`${index} 1`} /> },
      { senderId: 'ack', components: <WatsonMessageBox /> },
      { senderId: 'err', components: <ErrorMessageBox id={`${index} 1`} message={arg.chatText} /> },
      { senderId: 'student', components: <StudentMessageBox /> }
      ].forEach(({ senderId, components }) => {
        // console.log('Chatlist final senderId 1== ', senderId);
        // console.log('Chatlist final arg.senderId 1 == ', arg.senderId);
        // console.log('Chatlist components1 == ', components);
      // const result = Chatlist(id);
      // // console.log('Chatlist final == ', id);
        expect(arg.senderId).toBe('watson');
      });
      return arg.senderId;
    });
  });
  test('Should check the senderId be student in chatlist component', () => {
    component = shallow(<Chatlist
      messages={mockStudentMessages}
      retryAction={mockFn}
      retryMessage={mockStudentMessages.retryMessage}
      updateComponent={false}
    />);
    component.instance().props.messages.map((arg, index) => {
      [
      { senderId: 'watson', components: <WatsonMessageBox id={`${index} 1`} /> },
      { senderId: 'ack', components: <WatsonMessageBox /> },
      { senderId: 'err', components: <ErrorMessageBox id={`${index} 1`} message={arg.chatText} /> },
      { senderId: 'student', components: <StudentMessageBox /> }
      ].forEach(({ senderId, components }) => {
        // console.log('Chatlist final senderId 2 == ', senderId);
        // console.log('Chatlist final arg.senderId 2 == ', arg.senderId);
        // console.log('Chatlist components == ', components);
      // const result = Chatlist(id);
      // // console.log('Chatlist final == ', id);
        expect(arg.senderId).toBe('student');
      });
      return arg.senderId;
    });
  });
  test('Should check the senderId be ack in chatlist component', () => {
    component = shallow(<Chatlist
      messages={mockAckMessages}
      retryAction={mockFn}
      retryMessage={mockMessages.retryMessage}
      updateComponent={false}
    />);
    component.instance().props.messages.map((arg, index) => {
      [
      { senderId: 'watson', components: <WatsonMessageBox id={`${index} 1`} /> },
      { senderId: 'ack', components: <WatsonMessageBox /> },
      { senderId: 'err', components: <ErrorMessageBox id={`${index} 1`} message={arg.chatText} index={index + 10} /> },
      { senderId: 'student', components: <StudentMessageBox /> }
      ].forEach(({ senderId, components }) => {
        // console.log('Chatlist final arg.senderId 3 == ', arg.senderId);
        // console.log('Chatlist final id 3 == ', senderId);
        // console.log('Chatlist components == ', components);
      // const result = Chatlist(id);
      // // console.log('Chatlist final == ', id);
        expect(arg.senderId).toBe('ack');
      });
      return arg.senderId;
    });
  });

  test('Should check the senderId be err in chatlist component', () => {
    component = shallow(<Chatlist
      messages={mockErrMessages}
      retryAction={mockFn}
      retryMessage={mockMessages.retryMessage}
      updateComponent={false}
    />);
    component.instance().props.messages.map((arg, index) => {
      [
      { senderId: 'watson', components: <WatsonMessageBox id={`${index} 1`} /> },
      { senderId: 'ack', components: <WatsonMessageBox /> },
      { senderId: 'err', components: <ErrorMessageBox id={`${index} 1`} message={arg.chatText} index={index + 10} /> },
      { senderId: 'student', components: <StudentMessageBox /> }
      ].forEach(({ senderId, components }) => {
        // console.log('Chatlist final arg.senderId 3 == ', arg.senderId);
        // console.log('Chatlist final id 3 == ', senderId);
        // console.log('Chatlist components == ', components);
      // const result = Chatlist(id);
      // // console.log('Chatlist final == ', id);
        expect(arg.senderId).toBe('err');
      });
      return arg.senderId;
    });
  });

  test('Should check the chat Type in chatlist component', () => {
    component = shallow(<Chatlist
      messages={mockMessages}
      retryAction={mockFn}
      retryMessage={mockMessages.retryMessage}
      updateComponent={false}
    />);
    component.instance().props.messages.map((arg, index) => {
      [
      { senderId: 'watson', components: <WatsonMessageBox id={`${index} 1`} /> },
      { senderId: 'ack', components: <WatsonMessageBox /> },
      { senderId: 'err', components: <ErrorMessageBox id={`${index} 1`} message={arg.chatText} index={index + 10} /> },
      { senderId: 'student', components: <StudentMessageBox /> }
      ].forEach(({ senderId, components }) => {
        // console.log('Chatlist final senderId 4== ', senderId);
        // console.log('Chatlist final arg.senderId 4 == ', arg.senderId);
        // console.log('Chatlist components 4 == ', components);
      // const result = Chatlist(id);
      // // console.log('Chatlist final == ', id);
        expect(typeof arg.chatLabel).toBe('object');
        expect(arg.chatLabel.type).toBe('QUESTION');
      });
      return arg.senderId;
    });
  });
});

如果有任何错误,请更正。它对我有帮助。

0 个答案:

没有答案