简体   繁体   中英

How to spy only one react hook useState

I want to isolate the test to a targeted useState.

Lets say I have 3 useStates, of which some are in my component and some are in children components in this testcase.

Currently this logs for 3 different useStates. How to target the one I want. Lets say its called setMovies.

const createMockUseState = <T extends {}>() => {
  type TSetState = Dispatch<SetStateAction<T>>;
  const setState: TSetState = jest.fn((prop) => {
    // if setMovies ???
    console.log('jest - spy mock = ', prop); 
  });
  type TmockUseState =  (prop: T) => [T, TSetState];
  const mockUseState: TmockUseState = (prop) => [prop, setState];

  const spyUseState = jest.spyOn(React, 'useState') as jest.SpyInstance<[T, TSetState]>; 
  spyUseState.mockImplementation(mockUseState);
};
interface Props {
  propertyToTest: boolean
};

describe('Search Movies', () => {
  describe('Onload - do first search()', () => {
    beforeAll(async () => {
      createMockUseState<PROPS>(); 
      wrapper = mount(
          <ProviderMovies>
            <SearchMovies />
          </ProviderMovies>
      );  
      await new Promise((resolve) => setImmediate(resolve));
      await act(
       () =>
        new Promise<void>((resolve) => {
          resolve();
        })
      );
    });

  });
});

as we know react hooks depends on each initialization position. And for example if you have 3 hooks inside your component and you want to mock the 2-nd, you should mock 1 and 2 with necessary data. Something like this

//mock for test file
jest.mock(useState); // you should mock here useState from React

//mocks for each it block
const useMockHook = jest.fn(...);

jest.spyOn(React, 'useState').mockReturnValueOnce(useMockHook);

expect(useMockHook).toHaveBeenCalled();
// after that you can check whatever you need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM