开玩笑时模拟函数没有被调用

Xee*_*een 3 javascript unit-testing reactjs jestjs enzyme

我正在尝试测试:

onChange(value) {
  this.setState({ postcode: value });
  if (value.length >= 3) this.listSuggestions(value);
}
Run Code Online (Sandbox Code Playgroud)

通过写:

test("onChange updates the state", () => {
  const postalCodeWrapper = mount(<PostalCode />);
  const instance = postalCodeWrapper.instance();
  const listSuggestions = jest.fn(instance.listSuggestions);

  const mockValue = "this is mock value";
  instance.onChange(mockValue);
  expect(instance.state.postcode).toBe(mockValue);
  expect(listSuggestions).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)

而这又回来了Expected mock function to have been called, but it was not called.,谈论着listSuggestions。这是为什么?如果我删除该声明,也会发生同样的情况if (value.length >= 3)

Jar*_*ith 5

你的问题是这一行:

const listSuggestions = jest.fn(instance.listSuggestions);
Run Code Online (Sandbox Code Playgroud)

当你调用它时,jest.fn返回一个函数,而不是改变现有方法。您将其分配给 a const,但您的组件将调用原始组件。

将其更改为:

instance.listSuggestions = jest.fn(instance.listSuggestions);
Run Code Online (Sandbox Code Playgroud)

用模拟函数覆盖组件方法,假设条件检查通过,它将调用该函数。