测试时,React Props功能不确定



我正在构建一个涉及预算的React应用程序,我为BillContainer组件和AddBill组件编写了代码。

这是我的代码:

billcontainer.js

import React from 'react';
import BillList from './BillList';
import AddBill from './AddBill';
class BillContainer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      bills: [
      ]
    }
    this.addBill = this.addBill.bind(this)
  }
  addBill(bill) {
    this.setState((state) => ({
      bills: state.bills.concat([bill])
    }));
  }
  render() {
    return (
      <div>
      <AddBill addNew={this.addBill} />
        <BillList bills={this.state.bills} />
      </div>
    )
  }
}
export default BillContainer;

addbill.js

import React from 'react';
class AddBill extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      newBill: ''
    };
    this.updateNewBill = this.updateNewBill.bind(this)
    this.handleAddNew = this.handleAddNew.bind(this)
  }
  updateNewBill(e) {
    this.setState({
      newBill: e.target.value
    })
  }
  handleAddNew(bill) {
    this.props.addNew(this.state.newBill)
    this.setState({
      newBill: ''
    })
  }
  render() {
    return (
      <div>
        <input
          type='text'
          value={this.state.newBill}
          onChange={this.updateNewBill}
        />
        <button onClick={this.handleAddNew}> Add Bill </button>
      </div>
    )
  }
}
export default AddBill;

这是我的 addbill.test.js test:

import React from 'react';
import ReactDOM from 'react-dom';
import Enzyme from 'enzyme';
import { shallow, mount, render } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';
import AddBill from '../components/AddBill';
let Sinon = require('sinon')
Enzyme.configure({adapter: new EnzymeAdapter() });
it('Adds a bill to the list', () => {
  const clickSpy = Sinon.spy(AddBill.prototype, 'handleAddNew');
  const wrapper = shallow(
    <AddBill />
  );
  wrapper.find('button').simulate('click');
  expect(clickSpy.calledOnce).toEqual(true)
})

im试图测试当单击"添加帐单"按钮时添加新账单。我已将AddBill函数作为Prop传递,但测试正在抛出错误TypeError: this.props.AddNew is not a function

如何防止错误消息并使this.props.addNew()不确定?

您可以像这样使用jest.spyOn

it('Adds a bill to the list', () => {
  const wrapper = shallow(
    <AddBill addNew={() => {}} />
  );
  const clickSpy = jest.spyOn(wrapper.instance(), 'handleAddNew');
  wrapper.find('button').simulate('click');
  expect(clickSpy).toHaveBeenCalledTimes(1);
})

您不是通过AddNew属性:

const wrapper = shallow(
  <AddBill addNew={yourAddNewFunction} />
);

最新更新