Тестирование функции с использованием шутки и фермента - PullRequest
0 голосов
/ 22 ноября 2018

У меня есть функция, которая выглядит следующим образом:

getPhoneComp() {
    if (this.props.contactDetails.countPhone === 1)
      return (<PhoneComp contactDetails={this.props.contactDetails.phoneSet[0]} contactId={this.props.contactDetails.contactId} errorHandler={this.props.errorHandler} updateMobileNo={this.props.updateMobileNo} />);
    else if (this.props.contactDetails.countPhone === 2) {
      return (
        <div>
          <div className={classes.sceESpace}><PhoneComp contactDetails={this.props.contactDetails.phoneSet[0]} contactId={this.props.contactDetails.contactId} errorHandler={this.props.errorHandler} updateMobileNo={this.props.updateMobileNo} /></div>
          <div className={classes.sceESpace}><PhoneComp contactDetails={this.props.contactDetails.phoneSet[1]} contactId={this.props.contactDetails.contactId} errorHandler={this.props.errorHandler} updateMobileNo={this.props.updateMobileNo} /></div>
        </div>
      );

    } else if (this.props.contactDetails.countPhone === 3) {
      return (
        <div>
          <div className={classes.sceESpace}><PhoneComp contactDetails={this.props.contactDetails.phoneSet[0]} contactId={this.props.contactDetails.contactId} errorHandler={this.props.errorHandler} updateMobileNo={this.props.updateMobileNo} /></div>
          <div className={classes.sceESpace}><PhoneComp contactDetails={this.props.contactDetails.phoneSet[1]} contactId={this.props.contactDetails.contactId} errorHandler={this.props.errorHandler} updateMobileNo={this.props.updateMobileNo} /></div>
          <div className={classes.sceESpace}><PhoneComp contactDetails={this.props.contactDetails.phoneSet[2]} contactId={this.props.contactDetails.contactId} errorHandler={this.props.errorHandler} updateMobileNo={this.props.updateMobileNo} /></div>
        </div>
      );

    }
    else if (this.props.contactDetails.countPhone === 0) {
      return (
        <div />
      );
    }
  }

Затем в моей функции рендеринга я вызываю функцию, как показано ниже:

render() {
    return (
      <div>
        {this.getPhoneComp()}
      </div>

    );
  }

Итак, в настоящее время янаписание контрольного примера для этого компонента, как показано ниже:

 it('renders the Phone component', () => {
      let contactDetailsState={contactDetails:{
        webId:'', 
        contactId:'', 
        isContactPresent:true,
        firstName:'',
        lastName:'',
        middleName:'',
        customerSet:[{customerNumber:'1379',
        customerName:'K F I INCORPORATED',
        serviceAccountCount:2,
        customerContactRelationshipType:'Z00001',
        notificationEmailIndex:'E1',
        customerStatus:'',
        notificationVoiceIndex:'P2',
        customerType:'S',
        notificationPhoneIndex:'P1',
        contactId:'0104489742',
        notificationEmail:'xx1212@a.com',
        notificationVoice:'4564564564',
        notificationSms:'5656565566'}],
        emailSet:[{notificationEmail:'xx1212@a.com',
        notificationEmailIndex:'E1'},
        {notificationEmail:'xx1@a.com',notificationEmailIndex:'E2'}],
        emailSetWithNoAlert:[{notificationEmail:'xx1212@a.com',notificationEmailIndex:'E1'},
        {notificationEmail:'xx1@a.com',notificationEmailIndex:'E2'},
        {notificationEmail:'No email alerts',notificationEmailIndex:'NaN'}],
        phoneSet:[{notificationPhone:'5656565566',notificationPhoneIndex:'P1',
        notificationPhoneType:'M'},{notificationPhone:'4564564564',
        notificationPhoneIndex:'P2',notificationPhoneType:'L'}],phoneSetWithNoAlert
        :[{notificationPhone:'5656565566',notificationPhoneIndex:'P1',
        notificationPhoneType:'M'},{notificationPhone:'4564564564',
        notificationPhoneIndex:'P2',notificationPhoneType:'L'},
        {notificationPhone:'No Phone Alerts',notificationPhoneIndex:'NaN',
        notificationPhoneType:'L'},{notificationPhone:'No Text Alerts',
        notificationPhoneIndex:'NaN',notificationPhoneType:'M'}],
        mobileSet:[{notificationPhone:'5656565566',notificationPhoneIndex:'P1',notificationPhoneType:'M',contactId:'0104489742'}],
        isMobilePresent:true,countEmail:2,countPhone:2,countMobile:1,totalphoneCount:2,
        enrollCustomer:['1379'],suffix:'Jr.',prefix:'Mr.'}};


      let errorHandlerFn=jest.fn();
      let updateMobileNoFn=jest.fn();
      let getPhoneCompFn=jest.fn();
      let phoneComponent = mount(<PhoneContainer contactDetails={contactDetailsState} errorHandler={errorHandlerFn} updateMobileNo={updateMobileNoFn} getPhoneComp={getPhoneCompFn} />);
      expect(getPhoneCompFn).toHaveBeenCalled();
    });

Итак, я пытаюсь запустить функцию, но при выполнении этого теста я получаю следующую ошибку:

Expected mock function to have been called.

в expect(getPhoneCompFn).toHaveBeenCalled(); строке в тесте.Итак, как мне проверить, вызывается ли функция?

1 Ответ

0 голосов
/ 22 ноября 2018

getPhoneComp не опора, а метод.Так как это метод-прототип, его можно смоделировать на прототипе класса:

getPhoneCompFn=jest.spyOn(PhoneContainer.prototype, 'getPhoneComp')
.mockImplementation(() => {});

let phoneComponent = mount(<PhoneContainer ... />);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...