【问题标题】:Stubbing an action passed as a prop for unit test using jest in ReactJS在 ReactJS 中使用 jest 将作为道具传递给单元测试的动作存根
【发布时间】:2019-03-04 16:52:07
【问题描述】:

我正在为我的组件“UserDataView”中的一种私有方法“prepareUserCriteria”编写测试。

这反过来将数据传递给“requestProfile”方法,这实际上是一个动作。

为了测试“prepareUserCriteria”,我需要检查是否使用正确的数据调用了“requestProfile”。

但是,我收到如下错误 - “TypeError:试图将未定义的属性包装为函数”

我该如何解决这个问题?

代码如下:

组件:用户数据视图

prepareUserCriteria() {
 const criteria = this.state.searchCriteria;
 //Do some checks..
 if(...) {
    criteria = ......
 } else if(){
  criteria = .......
 } 

 return criteria;
} 

request(){
    //Do some checks...
    .............
    return this.props.dispatch.requestProfile({
        searchCriteria: this.prepareUserCriteria(),
        filters,
        ....
        //other arugments
        ....
        ....
    });
}

测试:

import React from 'react';
import { shallow } from 'enzyme';
import { requestProfile } from '../profile-actions';
import { spy, stub, assert as sinnonAssert } from 'sinon';
import { UserDataView } from '../user-data-view';
import moment from 'moment';

test('should test prepareUserCriteria logic', () => {
    const userSearchProps = {
        dispatch: spy(),
        joiningDate: moment('2018-12-12T00:00:00.000Z'),
        background: {},
        error: false,
        isCalendarLoading: false,
        clearFlightSelectionState: () => {
        },
        metadata: fromJS({
            userProfileType: 'EMP'
        }),
        searchCriteria: {
            address: [{ currentCity: 'FCO' }, { permanentCity: 'LIN' }],
            user: {
                firstName: 'John',
                lastName: 'Smith'
            },
            isValidUser: true
        }
    };
    userSearchProps.requestProfile = stub(requestProfile).callsFake(() => {});
    const userDataView = shallow(<UserDataView {...userSearchProps} />, context);
    sinonAssert.calledWith(userDataView.instance().props.dispatch.requestProfile, { 
        searchCriteria: {
            address: [{ currentCity: 'FCO' }, { permanentCity: 'LIN' }],
            user: {
             firstName: 'John',
                lastName: 'Smith'
            },
            isValidUser: true
        }
  });
});

【问题讨论】:

    标签: reactjs unit-testing ecmascript-6 jestjs stub


    【解决方案1】:
    TypeError: Attempted to wrap undefined property undefined as function
    

    可能意味着requestProfile 未定义。

    userSearchProps.requestProfile = stub(requestProfile).callsFake(() => {});
    

    检查导入。

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 2021-07-05
      相关资源
      最近更新 更多