getting error as a "useCounter" is read-only."

Viewed 49

I make a simple demo of counter I am using jest and enzyme for testing.I want to know if I click increment button it call increment button handler. but it is giving me this error

useCounter" is read-only.

here is my code https://codesandbox.io/s/awesome-jepsen-5os4e?file=/src/App.test.js

test("clicking button increment counter  i call increment function", () => {
  const f1 = jest.fn();
  useCounter = jest.fn(() => {
    return {
      state: "",
      increment: f1,
      decrement: null
    };
  });

  const wrapper = setup();

  // find button and click
  const button = findByTestAttr(wrapper, "increment-button");
  button.simulate("click");

  // find display and test value
  expect(f1).toHaveBeenCalled();
});

enter image description here

2 Answers

Looking at your sandbox example, it seems you are already importing useCounter

like import useCounter from "./useCounter";

And, then you're trying to update that variable(which isn't possible to do)

You should update your code like this

import * as counter from './useCounter' // declare named exports in useCounter
const f1 = jest.fn();
counter.useCounter = jest.fn(() => {
  f1,
});

Try to spy on it (and make sure it's not an arrow function):

jest.spyOn(useCounter, 'useCounter').mockImplementation(() => {
    //your mock implementation
});

Related