admin管理员组

文章数量:1356337

I'm trying to test:

onChange(value) {
  this.setState({ postcode: value });
  if (value.length >= 3) this.listSuggestions(value);
}

by writing:

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();
});

And this returns Expected mock function to have been called, but it was not called., talking about listSuggestions. Why is that? Same thing happens if I remove the if (value.length >= 3) statement.

I'm trying to test:

onChange(value) {
  this.setState({ postcode: value });
  if (value.length >= 3) this.listSuggestions(value);
}

by writing:

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();
});

And this returns Expected mock function to have been called, but it was not called., talking about listSuggestions. Why is that? Same thing happens if I remove the if (value.length >= 3) statement.

Share Improve this question edited Feb 14, 2019 at 17:21 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Feb 14, 2019 at 13:26 XeenXeen 7,01317 gold badges69 silver badges113 bronze badges 2
  • 1 Shouldn't const listSuggestions = jest.fn(instance.listSuggestions) be instance.listSuggestions = jest.fn(instance.listSuggestions)? – Jared Smith Commented Feb 14, 2019 at 13:30
  • 1 @JaredSmith thank you! That worked. – Xeen Commented Feb 14, 2019 at 13:33
Add a ment  | 

1 Answer 1

Reset to default 5

Your problem is this line:

const listSuggestions = jest.fn(instance.listSuggestions);

When you call that, jest.fn is returning a new function, not mutating the existing method. You assign it to a const, but your ponent will be calling the original.

Change it to:

instance.listSuggestions = jest.fn(instance.listSuggestions);

To overwrite the ponent method with the mock function, which it will then call assuming the conditional check passes.

本文标签: javascriptMock function not getting called in jestStack Overflow