0

My test involving a mock function (React, Enzyme and Jest) works:

it('should do a thing', () => {
  const myButton = wrapper.find('Button');
  expect(mockFunction.mock.calls.length).toBe(0);
  myButton.simulate('click');
  expect(mockFunction.mock.calls.length).toBe(1);
});

However when I try to simplify the code with a variable the test fails. numberClicks is 0 both times.

it('should do a thing', () => {
  const myButton = wrapper.find('Button');
  const numberClicks = mockFunction.mock.calls.length;
  expect(numberClicks).toBe(0);
  myButton.simulate('click');
  expect(numberClicks).toBe(1);
});

Is this normal JavaScript behaviour or some weirdness with the testing libraries?

Andreas
  • 21,535
  • 7
  • 47
  • 56
Evanss
  • 23,390
  • 94
  • 282
  • 505
  • 4
    Take a minute to think about what `const` stands for. – 04FS Mar 27 '19 at 13:50
  • But apart from that, no, this would not update automatically if it wasn’t a const either. `length` is a scalar property, so you assigned the current value here, not a reference as would happen with an object. – 04FS Mar 27 '19 at 13:52
  • You are not storing a reference to the object. Instead you are storing the length the object had at a specific time. Updating the original object doesn't update your variable. – r3dst0rm Mar 27 '19 at 13:53
  • Store `mockFunction.mock.calls` into a variable and it will work as you expect. –  Mar 27 '19 at 13:53
  • you assign the value in the variable and it is stored there. The .length property might change but its previious value is still stored in the variable `numberClicks`, either check the `.length` directly or re-assign the variable. the (primitive values in javascript) variable are assigned by value NOT by reference. Check these terms to see what they mean – Nikos M. Mar 27 '19 at 13:53

0 Answers0