Javascript 无法监视组件测试中的操作

Javascript 无法监视组件测试中的操作,javascript,reactjs,react-redux,chai-enzyme,Javascript,Reactjs,React Redux,Chai Enzyme,我正试图用柴间谍来测试一个被派遣的行动。我尝试过各种故障排除技术,但一直无法通过测试 我试图监视(component.prototype,'method)和(wrapper.instance().props.store,'dispatch'),但都没有成功 以下是组件代码: export class Appointments extends React.Component { componentDidMount() { this.props.dispatch(fetchA

我正试图用柴间谍来测试一个被派遣的行动。我尝试过各种故障排除技术,但一直无法通过测试

我试图监视
(component.prototype,'method)
(wrapper.instance().props.store,'dispatch')
,但都没有成功

以下是组件代码:

export class Appointments extends React.Component {
    componentDidMount() {
        this.props.dispatch(fetchAppointments(this.props.user.id));
    }

render() {
    if (this.props.appointments) {
        const list = this.props.appointments.map(l => {
            let appointmentDate = new Date(l.date);

                let day = appointmentDate.getDate();
                if (day < 10) {
                    day = `0${day}`
                }
                let month = appointmentDate.getMonth() + 1;
                if (month < 10) {
                    month = `0${month}`;
                }
                const year = appointmentDate.getFullYear();

                let formattedAppointmentDate = `${month}/${day}/${year}`;
            return {
                id: l._id,
                date: formattedAppointmentDate
            };
        });
        return (
           <div className={"create-appointment-div desktop-hide-2 " + (this.props.isAppointmentInfoShowing ? 'hidden-1' : '')}>
                        <span className={"create-appointment-span " + (this.props.isCreateAppointmentFormShowing ? 'hidden-1' : '')}>
                            Need to create an appointment?
                        </span>
                        <button
                            className={"create-appointment-button "  + (this.props.isCreateAppointmentFormShowing ? 'hidden-1' : '')}
                            onClick={() => this.props.dispatch(chooseCreateAppointment())}
                        >
                            Click here
                        </button>
                    </div>
                    <div className="create-appointment-div mobile-hide">
                        <span className={"create-appointment-span " + (this.props.isCreateAppointmentFormShowing ? 'hidden-1' : '')}>
                            Need to create an appointment?
                        </span>
                        <button
                            className={"create-appointment-button "  + (this.props.isCreateAppointmentFormShowing ? 'hidden-1' : '')}
                            onClick={() => this.props.dispatch(chooseCreateAppointment())}
                        >
                            Click here
                        </button>
                    </div>
                    <div className={"create-appointment-form-component-div " + (this.props.isCreateAppointmentFormShowing ? '' : 'hidden-1')}>
                        <CreateAppointmentForm />
                    </div> 
                </main>
                <Footer />
            </div>
        );
    }
}
}

const mapStateToProps = state => ({
    appointments: state.app.appointments,
    user: state.auth.currentUser,
    isCreateAppointmentFormShowing: state.app.isCreateAppointmentFormShowing,
    isAppointmentInfoShowing: state.app.isAppointmentInfoShowing,
    deletedAppointment: state.app.deletedAppointment,
    isMessageShowing: state.app.isMessageShowing,
    isLoading: state.app.isLoading
});

export default requiresLogin()(connect(mapStateToProps)(Appointments));
导出类组件{
componentDidMount(){
this.props.dispatch(fetch约会(this.props.user.id));
}
render(){
如果(本道具预约){
const list=this.props.appoints.map(l=>{
let appointmentDate=新日期(l.Date);
let day=appointmentDate.getDate();
如果(第10天){
day=`0${day}`
}
let month=appointmentDate.getMonth()+1;
如果(月<10){
月份=`0${month}`;
}
const year=任命日期。getFullYear();
让formattedAppointDate=`${month}/${day}/${year}`;
返回{
身份证号码:l.(身份证号码),
日期:formattedAppointmentDate
};
});
返回(
需要创建预约吗?
this.props.dispatch(chooseCreateAppointment())}
>
点击这里
需要创建预约吗?
this.props.dispatch(chooseCreateAppointment())}
>
点击这里
);
}
}
}
常量mapStateToProps=状态=>({
约会:state.app.appoints,
用户:state.auth.currentUser,
IsCreateAppointFormShowing:state.app.IsCreateAppointFormShowing,
isappointinfoshowing:state.app.isappointinfoshowing,
DeleteAdapPoint:state.app.DeleteAdapPoint,
isMessageShowing:state.app.isMessageShowing,
isLoading:state.app.isLoading
});
导出默认的requiresLogin()(connect(mapstatetops)(约会));
以下是测试代码:

import React from 'react';
import {shallow, mount} from 'enzyme';
import configureStore from 'redux-mock-store';
import {Provider} from 'react-redux';
import {MemoryRouter} from 'react-router';
import thunk from 'redux-thunk';
import chai, {expect} from 'chai';
import spies from 'chai-spies';

import Appointments from './appointments';
import NavigationBar from './navBar';
import Footer from './footer';
import AppointmentsList from './appointmentsList';
import AppointmentsShow from './appointmentsShow';
import CreateAppointmentForm from './createAppointmentForm';

const middlewares = [thunk];

const mockStore = configureStore(middlewares);

chai.use(spies);

const appointments = [
    {
      address: {
        street: '40 South Greenlake Ave',
        city: 'Jacksonville',
        state: 'FL',
        zipCode: 35421
      },
      _id: '5cb694034859fh37701f316e',
      description: 'Access evaluation',
      date: '2019-01-04T05:00:00.000Z',
      time: '2:15 p.m.',
      with: 'Jason Strickland',
      title: 'MD',
      where: 'Vascular Access Center',
      phoneNumber: '904-943-2942',
      patient: '5cb694034859f123701f3159'
    },
    {
      address: {
        street: '632 Oak St',
        city: 'Jacksonville',
        state: 'FL',
        zipCode: 34423
      },
      _id: '5cb694034859f123701f316d',
      description: 'Back pain',
      date: '2019-01-19T05:00:00.000Z',
      time: '12:30 p.m.',
      with: 'Jessica Brown',
      title: 'Primary care physician',
      where: 'Baptist Primary Care',
      phoneNumber: '904-233-1114',
      patient: '5cb694034859f123701f3159'
    },
    {
      address: {
        street: '402 South Lakeside Dr',
        city: 'Jacksonville',
        state: 'FL',
        zipCode: 35422
      },
      _id: '5cb694034859f123701f316f',
      description: 'Vein mapping',
      date: '2019-02-04T05:00:00.000Z',
      time: '2:10 p.m.',
      with: 'Jason Strickland',
      title: 'MD',
      where: 'Vascular Access Center',
      phoneNumber: '904-943-2942',
      patient: '5cb694034859f123701f3159'
    }
  ];

describe('<Appointments />', () => {
    let wrapper;
    let store;
    let initialState;
    beforeEach(() => {
        initialState = {
            app: {
                selectedAppointments: [],
                selectedLabResult: null,
                isSidebarShowing: false,
                labResults: [],
                isLabResultsInfoShowing: false,
                profile: [],
                loadedBasicProfileInfoFormData: {},
                isUserInfoShowing: false,
                section: 0,
                appointments: [],
                isAppointmentInfoShowing: false,
                areSublinksShowing: false,
                currentDoctor: 0,
                isCreateAppointmentFormShowing: false,
                isCreateDoctorFormShowing: false,
                isEditBasicProfileInfoFormShowing: false,
                selectedAppointmentToEdit: null,
                selectedDoctorToEdit: null,
                loadedAppointmentFormData: {},
                isDoctorMenuShowing: false,
                loadedDoctorFormData: {},
                doctors: [],
                areAppointmentsShowing: false,
                deletedAppointment: null,
                deletedDoctor: null,
                isLoading: true,
                animation: false,
                isEditAppointmentFormShowing: false,
                isEditDoctorFormShowing: false
            },
            auth: {
                loading: false,
                currentUser: {
                    _id: 1
                },
                error: null
            }
        };
        store = mockStore(initialState);
    });

    it('Should render without crashing', () => {
        shallow(<Appointments />);
    });

    it('Should simulate a click event when the button that renders the createAppointmentForm component is clicked', () => {
        initialState.app.appointments = appointments;
        initialState.app.isLoading = false;
        wrapper = mount(
            <Provider store={store}>
                <MemoryRouter initalEntries={['/appointments']}>
                    <Appointments />
                </MemoryRouter>
            </Provider>
        );
        console.log('props', wrapper.instance().props);
        const spy = chai.spy.on(wrapper.instance().props.store, 'dispatch');
        expect(wrapper.find('button.create-appointment-button').at(0).length).to.equal(1);
        wrapper.find('button.create-appointment-button').at(0).simulate('click');
        expect(spy).to.have.been.called();
    });
});
从“React”导入React;
从“酶”导入{shall,mount};
从“redux模拟存储”导入configureStore;
从'react redux'导入{Provider};
从“react路由器”导入{MemoryRouter};
从“redux thunk”导入thunk;
从“chai”导入chai,{expect};
从"柴间谍"进口间谍;;
从“/约会”导入约会;
从“/navBar”导入导航栏;
从“./Footer”导入页脚;
从“./AppointsList”导入任命列表;
从“/AppointsShow”导入任命演示文稿;
从“/createAppointForm”导入CreateAppointForm;
const middleware=[thunk];
const mockStore=configureStore(中间件);
使用(间谍);
康斯特任命=[
{
地址:{
街道:“南格林莱克大街40号”,
城市:“杰克逊维尔”,
声明:“FL”,
邮编:35421
},
_id:'5cb694034859fh37701f316e',
描述:“访问评估”,
日期:“2019-01-04T05:00:00.000Z”,
时间:下午2:15,
和“杰森·斯特里克兰”,
标题:“MD”,
其中:'血管通路中心',
电话号码:“904-943-2942”,
患者:“5cb694034859f123701f3159”
},
{
地址:{
街道:“橡树街632号”,
城市:“杰克逊维尔”,
声明:“FL”,
邮编:34423
},
_id:'5cb694034859f123701f316d',
描述:'背痛',
日期:“2019-01-19T05:00:00.000Z”,
时间:下午12:30,
用“杰西卡·布朗”,
标题:“初级保健医生”,
其中:'浸信会初级护理',
电话号码:“904-233-1114”,
患者:“5cb694034859f123701f3159”
},
{
地址:{
街道:“402南湖边Dr”,
城市:“杰克逊维尔”,
声明:“FL”,
邮编:35422
},
_id:'5cb694034859f123701f316f',
描述:'静脉映射',
日期:“2019-02-04T05:00:00.000Z”,
时间:下午2:10,
和“杰森·斯特里克兰”,
标题:“MD”,
其中:'血管通路中心',
电话号码:“904-943-2942”,
患者:“5cb694034859f123701f3159”
}
];
描述(“”,()=>{
让包装纸;
让商店;
让我们开始陈述;
在每个之前(()=>{
初始状态={
应用程序:{
选定的应用程序:[],
selectedLabResult:null,
isSidebarShowing:错,
实验结果:[],
IsLabresultsInfo显示:错误,
个人资料:[],
loadedBasicProfileInfoFormData:{},
isUserInfoShowing:false,
节:0,
任命:[],
IsAppointInfoshowing:false,
AresPublishShowing:错误,
医生:0,,
IsCreateAppointFormShowing:false,
isCreateDoctorFormShowing:false,
ISEDItBasicProfileInfo显示:false,
SelectedAppointToEdit:null,
SelectedDoctorEdit:空,
LoadedAppointFormData:{},
IsDoctorManushowing:错误,
loadedDoctorFormData:{},
医生:[],
区域点显示:假,
DeleteDapPoint:null,
deletedDoctor:null,
孤岛加载:是的,
动画:错,
ISEDItAppointFormShowing:false,
isEditDoc
● <Appointments /> › Should simulate a click event when the button that renders the createAppointmentForm component is clicked

AssertionError: expected { Spy 'object.dispatch' }
function (action) {
        if (typeof action === 'function') {
          return action(dispatch, getState, extraArgument);
        }

        return next(action);
      } to have been called

  300 |         expect(wrapper.find('button.create-appointment-button').at(0).length).to.equal(1);
  301 |         wrapper.find('button.create-appointment-button').at(0).simulate('click');
> 302 |         expect(spy).to.have.been.called();
      |                                  ^
  303 |     });
  304 | });
  305 | 

  at Object.called (src/components/appointments.test.js:302:34)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 11 passed, 12 total
Snapshots:   0 total
Time:        6.625s
Ran all test suites matching /appointments.test.js/i.
 // chooseCreateAppointmentFile - file from where chooseCreateAppointment is coming or 
 just spy on chooseCreateAppointment
 const spy = chai.spy.on(chooseCreateAppointmentFile, 'chooseCreateAppointment');
 expect(wrapper.find('button.create-appointment-button').at(0).length).to.equal(1);
 wrapper.update();
 wrapper.find('button.create-appointment-button').at(0).simulate('click');