@testing-library/react-hooks#renderHook TypeScript Examples

The following examples show how to use @testing-library/react-hooks#renderHook. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: hooks-utils.test.tsx    From anthem with Apache License 2.0 7 votes vote down vote up
describe("hooks-utils", () => {
  /**
   * To suppress "act" error warnings, see:
   *
   * - https://react-hooks-testing-library.com/usage/advanced-hooks
   * Should be fixed with React v16.9.0
   */
  beforeAll(() => {
    // tslint:disable-next-line
    console.error = jest.fn();
  });

  test("useDateTime", async () => {
    /* Setup hook */
    const date = new Date();
    const fn = () => useDateTime(date);
    const { result } = renderHook(fn);
    expect(result.current).toBe(date);
  });
});
Example #2
Source File: use-user.spec.tsx    From frontend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
it('should refresh me if login succeeded', async () => {
  const { result } = renderHook(() => useUser(), { wrapper })

  mockLogin(200)
  await result.current.login('fakeuser', 'fakepassword', 'fake-token')
  await waitFor(() => {
    expect(result.current.user).toMatchSnapshot()
  })
})
Example #3
Source File: useToggle.test.ts    From baleen3 with Apache License 2.0 6 votes vote down vote up
test('can still force value', () => {
  const { result } = renderHook(() => useToggle(false))
  expect(result.current[0]).toBe(false)

  act(() => {
    result.current[2](true)
  })

  expect(result.current[0]).toBe(true)
})
Example #4
Source File: useMemo.test.ts    From use-memo-value with MIT License 6 votes vote down vote up
test("basics", t => {
	let { result } = renderHook(() => {
		let [rawValue, setRawValue] = useState({ name: "starting value" })
		let memoValue = useMemoValue(rawValue)
		return { rawValue, setRawValue, memoValue }
	})

	// init
	t.is(result.current.rawValue, result.current.memoValue)

	// update to same value
	act(() => result.current.setRawValue({ name: "starting value" }))
	t.not(result.current.rawValue, result.current.memoValue)
	t.is(result.current.memoValue.name, "starting value")

	// update to new value
	act(() => result.current.setRawValue({ name: "changed value" }))
	t.is(result.current.rawValue, result.current.memoValue)
	t.is(result.current.memoValue.name, "changed value")
})
Example #5
Source File: useDebounce.spec.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
it('should call the callback again after the cooldown period', async () => {
  const mock = jest.fn();
  const { result } = renderHook(() => useDebounce(mock, 10));
  const [callback] = result.current as ReturnType<typeof useDebounce>;
  callback();
  await waitFor(() => expect(mock).toBeCalledTimes(1));
  callback();
  await waitFor(() => expect(mock).toBeCalledTimes(2));
});
Example #6
Source File: useCroct.test.tsx    From plug-react with MIT License 6 votes vote down vote up
describe('useCroct', () => {
    it('should fail if used out of the <CroctProvider/> component', () => {
        jest.spyOn(console, 'error').mockImplementation();

        const {result} = renderHook(() => useCroct());

        expect(console.error).toBeCalled();

        expect(result.error?.message)
            .toBe('useCroct() can only be used in the context of a <CroctProvider> component.');
    });

    it('should return the Plug instance', () => {
        const {result} = renderHook(() => useCroct(), {
            wrapper: ({children}) => (<CroctContext.Provider value={{plug: croct}}>{children}</CroctContext.Provider>),
        });

        expect(result.current).toBe(croct);
    });
});
Example #7
Source File: testimonyListing.test.ts    From advocacy-maps with MIT License 6 votes vote down vote up
describe("usePublishedTestimonyListing", () => {
  it.each(cases)(
    "lists for user $user, bill $bill, filter $filter",
    async ({ user, bill, filter }) => {
      let uid: string | undefined = undefined
      if (user) {
        ;({ uid } = await testAuth.getUserByEmail(user))
      }
      const { result, waitFor } = renderHook(() =>
        usePublishedTestimonyListing({ billId: bill, uid })
      )
      act(() => void result.current.setFilter(filter))
      await waitFor(() => expect(result.current.items.loading).toBeFalsy())
      expect(result.current.items.error).toBeUndefined()
      const testimony = result.current.items.result!
      expect(testimony).not.toHaveLength(0)
    }
  )
})
Example #8
Source File: WherePanel.context.test.tsx    From ke with MIT License 6 votes vote down vote up
testProp(
  'useWhereContext got data from WhereProvider',
  [filtersArbitrary, handleFiltersArbitrary],
  (filtersValue, handleChange) => {
    const wrapper = ({ children }: PropsWithChildren<{}>): JSX.Element => (
      <WhereProvider filters={filtersValue} onFiltersChange={handleChange}>
        {children}
      </WhereProvider>
    )

    const { result } = renderHook(() => useWhereFilters(), { wrapper })

    expect(result.current).toEqual([filtersValue, handleChange])
  }
)
Example #9
Source File: main.test.ts    From sdc-ide with MIT License 6 votes vote down vote up
test.skip('applyMappings', async () => {
    const { result, waitFor } = renderHook(() => useMain(questionnaireIdInitial));

    await waitFor(() => {
        const batchRequest = ensure(result.current.batchRequestRD);
        expect(batchRequest.entry?.[0].resource.birthDate).toEqual('1980-01-01');
    });
    // TODO: finish this test
});
Example #10
Source File: useDrag.test.ts    From overwolf-hooks with MIT License 6 votes vote down vote up
describe('useDrag values', () => {
  it('should return useDrag functions', () => {
    const { result } = renderHook(() =>
      useDrag('test-element', { displayLog: true }),
    )
    const {
      onDragStart,
      onMouseMove,
      setCurrentWindowID,
      ...props
    } = result.current
    expect(props).not.toBeUndefined()
    expect(onDragStart).toBeInstanceOf(Function)
    expect(onMouseMove).toBeInstanceOf(Function)
    expect(setCurrentWindowID).toBeInstanceOf(Function)
  })
})
Example #11
Source File: use-user.spec.tsx    From frontend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
it.each`
  statusCode | resp | expectedError
  ${401} | ${{ detail: { remain: 4 } }} | ${new PasswordUnMatchError(4)}
  ${400} | ${{}} | ${new Error(LoginErrorCode.E_REQUEST_ERROR)}
  ${422} | ${{}} | ${new Error(LoginErrorCode.E_CLIENT_ERROR)}
  ${418} | ${{}} | ${new Error(LoginErrorCode.E_UNKNOWN_ERROR)}
  ${502} | ${{}} | ${new Error(LoginErrorCode.E_SERVER_ERROR)}
`('should return error if request is failed with failed status $statusCode', async ({ statusCode, resp, expectedError }) => {
  const { result } = renderHook(() => useUser(), { wrapper })

  mockLogin(statusCode, resp)

  expect.assertions(1)
  await expect(result.current.login('fakeuser', 'fakepassword', 'fake-token')).rejects.toEqual(
    expectedError
  )

  await waitFor(() => {})
})
Example #12
Source File: hooks.test.ts    From backstage with Apache License 2.0 6 votes vote down vote up
describe('hooks', () => {
  describe('useShadowRoot', () => {
    it('should return shadow root', async () => {
      const { result } = renderHook(() => useShadowRoot());

      expect(result.current?.innerHTML).toBe(shadowRoot.innerHTML);
    });
  });

  describe('useShadowRootElements', () => {
    it('should return shadow root elements based on selector', () => {
      const { result } = renderHook(() => useShadowRootElements(['h1']));

      expect(result.current).toHaveLength(1);
    });
  });

  describe('useShadowRootSelection', () => {
    it('should return shadow root selection', async () => {
      const { result } = renderHook(() => useShadowRootSelection(0));

      expect(result.current).toBeNull();

      fireSelectionChangeEvent(window);

      await waitFor(() => {
        expect(result.current?.toString()).toEqual('his ');
      });
    });
  });
});
Example #13
Source File: login.hooks.spec.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
describe('useLogin specs', () => {
  it('should return an object: credential with default values and setCredential a function when it calls it', () => {
    // Arrange

    // Act
    const { result } = renderHook(() => useLogin());

    // Assert
    const defaultCredential: Credential = { name: '', password: '' };
    expect(result.current.credential).toEqual(defaultCredential);
    expect(result.current.setCredential).toEqual(expect.any(Function));
  });

  it('should update credential when it calls setCredential', () => {
    // Arrange
    const newCredential: Credential = { name: 'admin', password: 'test' };

    // Act
    const { result } = renderHook(() => useLogin());

    act(() => {
      result.current.setCredential(newCredential);
    });

    // Assert
    expect(result.current.credential).toEqual(newCredential);
  });
});
Example #14
Source File: useEntity.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('useEntity', () => {
  it('should throw if no entity is provided', async () => {
    const { result } = renderHook(() => useEntity(), {
      wrapper: ({ children }) => <EntityProvider children={children} />,
    });

    expect(result.error?.message).toMatch(/entity has not been loaded/);
  });

  it('should provide an entity', async () => {
    const entity = { kind: 'MyEntity' } as Entity;
    const { result } = renderHook(() => useEntity(), {
      wrapper: ({ children }) => (
        <EntityProvider entity={entity} children={children} />
      ),
    });

    expect(result.current.entity).toBe(entity);
  });
});
Example #15
Source File: language.hooks.spec.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
describe('useLanguage specs', () => {
  it('should return a message with language equals "en" when it renders the hook', () => {
    // Arrange

    // Act
    const { result } = renderHook(() => useLanguage(), { wrapper: LanguageProvider });

    act(() => {
      result.current.setLanguage('en');
    });

    // Assert
    expect(result.current.message).toEqual('The current language is: en');
  });
});
Example #16
Source File: useAuth.test.tsx    From react-starter-boilerplate with MIT License 6 votes vote down vote up
describe('useAuth', () => {
  test('adds token to session storage', async () => {
    mockServer();
    const { result } = renderHook(() => useAuth(), {
      wrapper: ({ children }) => (
        <AppProviders>
          <>{children}</>,
        </AppProviders>
      ),
    });

    await act(() => result.current?.login({ password: 'foo', username: 'bar' }));
    expect(global.sessionStorage.getItem('accessToken')).toBe('MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3');
  });
});
Example #17
Source File: useCoingeckoTokenPrices.test.tsx    From useDApp with MIT License 6 votes vote down vote up
describe('useCoingeckoTokenPrices', () => {
  it('works', async () => {
    const { result, waitForNextUpdate } = renderHook(() => useCoingeckoTokenPrices(ADDRESSES))
    expect(result.current).to.be.undefined
    await waitForNextUpdate()
    expect(result.error).to.be.undefined
    expect(result.current).to.be.an('array')
    expect(result.current?.length).to.eq(3)
    expect(result.current![0]).to.be.a('number')
  })
})
Example #18
Source File: index.test.tsx    From useTable with MIT License 6 votes vote down vote up
describe('<%= name %>', () => {
  it('should be defined', () => {
    expect(<%= name %>).toBeDefined();
  });

  it('success', async () => {
    const { result } = renderHook(() => <%= name %>());
    expect(result.current).toBe(true);
  });
});
Example #19
Source File: useSpreadSheet-spec.ts    From S2 with MIT License 6 votes vote down vote up
describe('useSpreadSheet tests', () => {
  const container = getContainer();
  const props: SheetComponentsProps = {
    spreadsheet: () => new PivotSheet(container, mockDataConfig, s2Options),
    options: s2Options,
    dataCfg: mockDataConfig,
  };

  test('should build spreadSheet', () => {
    const { result } = renderHook(() =>
      useSpreadSheet({ ...props, sheetType: 'pivot' }),
    );
    expect(result.current.s2Ref).toBeDefined();
  });

  test('should cannot change table size when width or height updated and disable adaptive', () => {
    const { result } = renderHook(() =>
      useSpreadSheet({ ...props, sheetType: 'pivot', adaptive: false }),
    );
    const s2 = result.current.s2Ref.current;

    expect(s2.options.width).toEqual(s2Options.width);
    expect(s2.options.height).toEqual(s2Options.height);
    act(() => {
      s2.setOptions({ width: 300, height: 400 });
    });

    const canvas = s2.container.get('el') as HTMLCanvasElement;
    expect(s2.options.width).toEqual(300);
    expect(s2.options.height).toEqual(400);

    expect(canvas.style.width).toEqual(`200px`);
    expect(canvas.style.height).toEqual(`200px`);
  });
});
Example #20
Source File: use-auth.test.tsx    From auth0-react with MIT License 6 votes vote down vote up
describe('useAuth0', () => {
  it('should provide the auth context', async () => {
    const wrapper = createWrapper();
    const {
      result: { current },
      waitForNextUpdate,
    } = renderHook(useAuth0, { wrapper });
    await waitForNextUpdate();
    expect(current).toBeDefined();
  });

  it('should throw with no provider', () => {
    const {
      result: { current },
    } = renderHook(useAuth0);
    expect(current.loginWithRedirect).toThrowError(
      'You forgot to wrap your component in <Auth0Provider>.'
    );
  });
});
Example #21
Source File: AppContext.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
describe('v1 consumer', () => {
  function useMockAppV1(): AppContextV1 {
    const impl = useVersionedContext<{ 1: AppContextV1 }>(
      'app-context',
    )?.atVersion(1);
    if (!impl) {
      throw new Error('no impl');
    }
    return impl;
  }

  it('should provide an app context', () => {
    const mockContext: AppContextV1 = {
      getPlugins: jest.fn(),
      getComponents: jest.fn(),
      getSystemIcon: jest.fn(),
    };

    const renderedHook = renderHook(() => useMockAppV1(), {
      wrapper: ({ children }) => (
        <AppContextProvider appContext={mockContext} children={children} />
      ),
    });
    const result = renderedHook.result.current;

    expect(mockContext.getPlugins).toHaveBeenCalledTimes(0);
    result.getPlugins();
    expect(mockContext.getPlugins).toHaveBeenCalledTimes(1);

    expect(mockContext.getComponents).toHaveBeenCalledTimes(0);
    result.getComponents();
    expect(mockContext.getComponents).toHaveBeenCalledTimes(1);

    expect(mockContext.getSystemIcon).toHaveBeenCalledTimes(0);
    result.getSystemIcon('icon');
    expect(mockContext.getSystemIcon).toHaveBeenCalledTimes(1);
    expect(mockContext.getSystemIcon).toHaveBeenCalledWith('icon');
  });
});