开玩笑的模拟间谍功能,未在测试中调用

时间:2019-07-08 22:24:24

标签: javascript reactjs jestjs spy

组件:

带有onChange处理程序的Input组件:

<Field
    component={FormattedTextInput}
    className={colMd113}
    name={NAMES.VEHICLE_YEAR}
    label={constants.VEHICLE_YEAR}
    validate={[required, validator.validateYearOfVehicle]}
    formatting="9999"
    onChange={this.yearOnChange}
/>

方法:

constructor(props) {
    super(props);

    this.yearOnChange = this.yearOnChange.bind(this)
}

yearOnChange(event) {
    if (event.target && event.target.value) {
        const value = event.target.value;
        this.setState({
            year: value
        });
    }
}

测试

it('yearOnChange method is called', function() {
    const spy = jest.spyOn(wrapper.instance(), 'yearOnChange');
    wrapper.update();
    // const instance = wrapper.instance();
    // console.log('instance', instance);
    wrapper.simulate('change', {
        target: {
            name: 'vehicleYear',
            value: '1999'
        }
    });
    expect(spy).toHaveBeenCalled();
});

错误

Vehicle Picker Component › yearOnChange method is called

   expect(jest.fn()).toBeCalled()

   Expected mock function to have been called, but it was not called.

     50 |         console.log(wrapper.instance())
     51 |
   > 52 |         expect(spy).toBeCalled();
        |                     ^
     53 |     });

这就是我登录wrapper.instance()

时看到的内容
VehiclePicker {
       props: {},
       context: {},
       refs: {},
       updater:
        Updater {
          _renderer:
           ReactShallowRenderer {
             _context: {},
             _element: [Object],
             _instance: [Circular],
             _newState: null,
             _rendered: [Object],
             _rendering: false,
             _forcedUpdate: false,
             _updater: [Circular],
             _dispatcher: [Object],
             _workInProgressHook: null,
             _firstWorkInProgressHook: null,
             _isReRender: false,
             _didScheduleRenderPhaseUpdate: false,
             _renderPhaseUpdates: null,
             _numberOfReRenders: 0 },
          _callbacks: [] },
       state:
        { year: '',
          make: '',
          makeArray: [],
          model: '',
          modelArray: [],
          token: '' },
       yearOnChange: [Function: bound yearOnChange],
       makeOnChange: [Function: bound makeOnChange],
       setState: [Function] }

更新

使用以下代码,expect(result).toEqual('1999')测试成功!但是expect(spy).toHaveBeenCalled()仍然没有:((当我实例化方法yearOnChange并实际更改组件中的状态时,怎么还没有检测到间谍被调用?

it('yearOnChange method is called', function() {
   const spy = jest.spyOn(VehiclePicker.prototype, 'yearOnChange');
   wrapper.instance().forceUpdate();

   const event = {
       target: {
           value: '1999'
       }
   };

   wrapper.instance().yearOnChange(event);
   wrapper.simulate('change', event);

   const result = wrapper.state('year');
   console.log('result', result); // result = 1999
   expect(result).toEqual('1999');
   expect(spy).toHaveBeenCalled();
});

2 个答案:

答案 0 :(得分:1)

已修复!

从这里的答案中获得了很大的帮助:Jest spyOn function called

这是我所缺少的重要步骤:

const instance = wrapper.instance()
const spy = jest.spyOn(instance, 'yearOnChange')

使用2个有效的expects更新了工作测试。

it('yearOnChange method is called', function() {
    const instance = wrapper.instance();  // <-- Needed to do this here
    const spy = jest.spyOn(instance, 'yearOnChange');  // <-- Then use instance here
    wrapper.instance().forceUpdate();

    const event = {
        target: {
            value: '1999'
        }
    };

    wrapper.instance().yearOnChange(event);
    wrapper.simulate('change', event);

    const result = wrapper.state('year');
    console.log('result', result); // result = 1999
    expect(result).toEqual('1999');
    expect(spy).toHaveBeenCalled();
});

答案 1 :(得分:0)

您是在手动监视并调用yearOnChange。

尝试不调用wrapper.instance()。yearOnChange(event);

调用wrapper.instance().onChange事件,或者像您一样,运行Simulation('change')就足够了。

您也可以尝试VehiclePicker.prototype.yearOnChange = jest.fn()

expect(VehiclePicker.prototype.yearOnChange).toBeCalled();