在 React 中测试组件方法

Testing component methods in React

我不明白为什么这不起作用...

我正在尝试测试这个功能:

  export class Main extends React.Component {

  handleName = (name) => (value) => {
   const prevState = this.state[name]
   this.setState({ [name]: {...prevState, name: value } })
  }

 render(){
   return(
     //some things
   )
 }
}

我的测试是(在 mocha 中):

it('expects handleName to have been called on change', () => {
  wrapper.find('.teamInput').at(0).simulate('change');
  expect(wrapper.instance().handleName().called).to.equal(true);
});

我认为这是正确的测试方法。我收到一条错误消息:expected undefined to equal true

当我 console.log(wrapper.instance().handleName()) 它说它是一个函数,所以它知道它在那里....

我的每个之前:

describe('Main Component', () => {
  let wrapper;
  const teamsStub = [];
  const matchesStub = [];
  const submitMatchStub = sinon.spy();
  const syncFirebaseToStoreStub = sinon.spy();
  beforeEach(() => {
    wrapper = mount(
      <Main
        teams={teamsStub}
        matches={matchesStub}
        submitMatch={submitMatchStub}
        syncFirebaseToStore={syncFirebaseToStoreStub}
      />
    )
  })
expect(wrapper.instance().handleName().called).to.equal(true);

called 方法仅适用于间谍。因此,例如,您将 submitMatch 的间谍传递给您的组件。如果您尝试测试使用此方法的任何地方的工作流程,您可以在那里检查该方法是否被调用或未在传递的间谍上调用 called。但是因为 handleName 是组件中的一个内部方法,所以您无法监视它。所以以上是无效的。

如果您修改代码以便从外部将 handleName 方法作为 prop 传递。然后在你的单元测试中,你可以为它传递一个 sinon 间谍并使用 called.

验证它