87 questions
0
votes
1
answer
281
views
testing-library/react-hooks calling a function that change the state
I tried everything but still for some reason the react state doesn't change, what is I am missing or what is the alternative approach?
Code:
export const useCounter = (): UseCounterResult => {
...
0
votes
2
answers
918
views
How can I test two different GET queries in the same React custom hook using react testing library and react-hooks?
I'm using a custom react hook to perform two GET operations using react query. The API is in a separate module and uses both getTestByUid() and getTestStatuses() inside useQuery.
// TestHook.js
import ...
1
vote
0
answers
397
views
react-hooks-testing-library: Context Provider, state change in child function act() error
I am using the React renderHook() function to call a custom hook. Internally in the custom hook, I call a function that executes axios, gets data and on success, dispatches a state change to a custom ...
0
votes
0
answers
301
views
How to test this window resize hook?
I've created a widget component that can be embedded on a webapp as a script. It is not embedded in an IFrame therefore lives inside the webapp's window object. This embedded component is responsive ...
1
vote
1
answer
354
views
React testing custom hook with window.url
I have a custom hook that downloads a file from an url, it works fine and now I trying to test its behaviour.
const useFileDownload = ({ apiResponse, fileName }) => {
const ref = useRef(null)
...
0
votes
0
answers
290
views
How can I test useEffect with async function in Jest?
I have this function inside a helper:
export const useDAMProductImages = (imageId: string) => {
const {
app: { baseImgDomain },
} = getConfig();
const response: MutableRefObject<...
0
votes
0
answers
1k
views
result.current.data is undefined when I declare renderHook into the test closure but works when it is defined outside of it
I'm trying to test a custom hook but for some reason I can't render the hook inside the test closure "it".
This code works (I must use the rerender methods otherwise the result.current.data ...
1
vote
2
answers
3k
views
TypeError: navigation.navigate is not a function in jest
Here is touchable element with navigation.navigate (react navigation 6.x),
export default Home = ({ navigation }) => {
....
return (
<TouchableOpacity testID={"...
1
vote
1
answer
2k
views
Testing custom hooks react typescript
Im learning react testing and i have this hook i want to test but i have no idea how
import { useState, useCallback } from 'react';
import axios from 'axios';
export const useFetch = () => {
...
-1
votes
1
answer
313
views
Handling state of select tag in dynamic input field react
I do not understand why the state is registered yet it does not have an effect to the intended value of beds.
Here is the main component
const options = ["1", "2", "3"];
...
1
vote
0
answers
2k
views
Vitest + MSW - Runtime request handler is not working
I'm trying to migrate the test framework of my app from Jest to Vitest (for multiple reasons) and I encounter an issue.
With Jest, I was using runtime request handlers at multiple places of my app to ...
0
votes
2
answers
533
views
not able to install react-google-login
Trying to install "react-google-login" by using the command
npm install react-google-login.
It gives the following error :
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve ...
2
votes
1
answer
181
views
react page doesnt render when getting the data back from server
react won't work when rendering the page, but when i changed code in the vscode (added a line of console or comment one line out), the page is rendered. or when page is not rendered. when i hit ...
1
vote
1
answer
1k
views
React Testing Library - mock offsetWidth, offsetLeft
I need your help on fixing the test case. I am trying to mock the document body offsetwidth, offsetLeft objects.
In the resize method, I am trying to mock the newWidth which is calculating the mouse ...
4
votes
2
answers
9k
views
What is the suitable type for renderHook in react-testing-library and TypeScript?
I wanna test a custom hook with react-testing-library therefore, I add this code into beforeEach:
let renderedHook ;
beforeEach(() => {
renderedHook = renderHook(() => useFetch());
});
test('...
2
votes
1
answer
5k
views
How can I test React custom hook with RTL which uses react-query?
I've a custom React hook which uses react-query useQuery() in it-self:
const useFetchSomething = () => {
const { data, isLoading } = useQuery('key', ....);
return .......
}
I had to create a ...
5
votes
2
answers
10k
views
Testing hooks which throw errors
The [deprecated?] react-hooks-testing-library would return any errors thrown by the hook under test.
Probably my misunderstanding, but it looks like implementation now in the main @testing-library/...
4
votes
1
answer
3k
views
React Testing Library merged with @testing-library/react-hooks, wrapper inconsistent in renderHook
With @testing-library/react-hooks I used to pass mocked store through initialProps just as mentioned in Advanced Hooks docs. Let's assume I have a code:
import configureMockStore from 'redux-mock-...
0
votes
1
answer
198
views
Assert that a function changes a stateful value
So, here is a simplified version of my code.
This is my custom hook.
export const useStep = () => {
const [step, setStep] = useState<Steps>("sending");
const changeStep = (...
1
vote
1
answer
1k
views
How to mock useRouter parameters for react-hooks-testing-library?
I have a custom hook, which has structure of:
const urlHook = () => {
const router = useRouter();
const read = () => {
return validate(router.query.param);
}
const write = (params) => {
...
1
vote
0
answers
2k
views
Formik useFormikContext testing with testing-library
I am trying to write some unit tests for my input components, most of them are connected to Formik and there are cases like my Autocomplete component where the form gets validated when the user ...
0
votes
0
answers
83
views
React hooks unit testing React.memo on a function
How can I test this function wrapped in the React.memo , below is the function :
const InternalDocuments = memo(
forwardRef<FormikProps<BlocksTypes>, InternalDocumentsProps>(
...
0
votes
1
answer
201
views
`@testing-library/react-hooks` is loading my whole project?
I think this is an issue with module resoltuion/babel/typescript.
When using @testing-library/react-hooks, I'm running into a strange stack:
FAIL src/hooks/useAllPayouts.test.tsx
● Test suite ...
3
votes
0
answers
2k
views
Unit testing a custom hook - "Invalid hook call. Hooks can only be called inside of the body of a function component"
Background:
I've created a custom hook for useModal() to wrap some state for creating/destroying modals around the application:
import { useState } from "react";
export default function ...
1
vote
1
answer
798
views
Testing React Native Image.getSize: Cannot spyOn on a primitive value; string given
I have a hook that detects the orientation of a React Native Image:
import { useState, useEffect } from 'react'
import { Image } from 'react-native'
const useFindImageSize = (image) => {
const [...
1
vote
0
answers
888
views
TypeError: Cannot read property 'hasOwnProperty' of undefined in renderHook import
I am trying to use renderHook from the testing-library.
When I run my test I get this error, TypeError: Cannot read property 'hasOwnProperty' of undefined
package.json
"devDependencies": {
...
2
votes
2
answers
2k
views
How to test that dispatch only gets called once
I have a custom hook that dispatches an action when a URL parameter changes:
export const useUser = (): void => {
const dispatch = useDispatch();
const { user } = useParams<{ user: string }&...
0
votes
1
answer
2k
views
How can I grab multiple mapped elements using useRef?
Here I map though an array of objects that contain images to display on a page. At the moment when I try useRef it only grabs me the very last element. How can I have it so that my useRef grabs me ...
0
votes
1
answer
3k
views
Unit testing a custom hook to ensure that it calls another hook
How can we ensure that a custom hook actually calls a method exposed by another hook?
Let's say, I have a custom hook useName that internally leverages useState.
import { useState } from 'react'
...
2
votes
1
answer
2k
views
Receiving a `globalObj.setTimeout is not a function` error for basic jest test
I am attempting to test a basic Axios hook and am receiving:
TypeError: globalObj.setTimeout is not a function
at setImmediatePolyfill (node_modules/@testing-library/react-native/build/helpers/...
8
votes
1
answer
5k
views
When to use waitForNextUpdate rather than act + jest.advanceTimersByTime?
There is an example on advanced-hooks#async doc.
I am confused about how does waitForNextUpdate works. I made two test cases to compare waitForNextUpdate and act() + jest.advanceTimersByTime().
index....
3
votes
1
answer
4k
views
Testing custom hook with SetTimeout and useEffect with Jest
I'm trying to test a relatively simple custom hook that uses useEffect and setTimeout. However, my test fails, and I cannot figure out what is wrong.
Here is the hook itself(useTokenExpirationCheck.ts)...
2
votes
1
answer
1k
views
Destructuring need waitFor
Why does destructuring need waitFor?
Codesandbox
All tests do the same thing. In the 'ok.test.ts' file I use renderHook, I use result.current[1] to set the state and result.current[0] to get the ...
3
votes
2
answers
2k
views
Can't mock useAsync with react test library
I am attempting to test a component that uses the useAsync hook using the @testing-library/react .
If I use jest.mock on the TestAPI module, followed by getTest.mockResolvedValueOnce(testArray); on ...
2
votes
1
answer
2k
views
The current result of a custom hook is updated when testing using react-hooks-testing-library
I am testing the custom React Hook shown below. Its functionality is to get the size of an image and then use the props provided to calculate the size of the image that the user wants.
import { ...
2
votes
1
answer
2k
views
How to mock a function that will have then and catch block?
I using Firebase authentication and I would like to test the function using Jest and react-hooks-testing-library.
I have a function that like this:
const loginWithEmailPassword = (email: string, ...
1
vote
1
answer
860
views
Get Firebase Error: No Firebase App '[DEFAULT]' has been created when using React-hooks-testing-library with jest
I using Firebase auth in React, and I try to test it with react-hooks-testing-library. The code I write is working. But when I try to test with react-hooks-testing-library I get this error:
...
1
vote
1
answer
4k
views
How to test internal functions using react hooks testing library?
I have a custom hook that I am trying to write tests for using the react hooks testing library package and I would like to know how I can test internal functions that are not returned in the custom ...
2
votes
1
answer
2k
views
How can we test a customHook with useEffect with no return values inside by triggering it multiple times?
Hi all I am new to jest and now working on some tests for our customHooks.
My customHook has useEffect inside and does not return value:
const useCustomHook = (func: EffectCallback, deps?: ...
-1
votes
2
answers
9k
views
React Intl Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry
I have used latest version of React-intl(^5.20.2). Trying to achieve Enzyme Unit testing in React hook component. but throwing this error "[React Intl] Could not find required intl object. needs ...
1
vote
1
answer
3k
views
Testing async custom hooks that useEffect with react-hooks-testing-library
I've written a simple React hook and want to test it with react-hooks-testing-library.
This hook calls an async function once both provider and domain variables, then once it's resolved puts data in ...
2
votes
1
answer
2k
views
How to test Async calls in JEST using request without mocking and awaits for react-hooks testing library
I am not good at writing tests as far as non API functionalities are concerned I have tested using JEST with the help of rendererHook Just like below Sample correct TEST:
import { render, screen, ...
2
votes
1
answer
6k
views
How to use react-testing-library and jest with mocked custom react hook updating?
Look at the following custom hook. The premise is that it updates its state when query changes.
export function UseCustomHook() {
const { query } = useRouter()
const [state, setState] = useState({}...
2
votes
2
answers
6k
views
waitFor times out after calling renderHook()
I am trying to test a simple custom hook:
export const getSearchResults = async (searchText: string) => {
const { data } = await axios.get(`${BASE_URL}/search`, {
params: {
searchText,
...
0
votes
0
answers
378
views
Get State from React Hook Testing
I'm having a problem trying to access state and setState using react-hooks-testing-library.
I've followed examples from various sources using Provider but it doesn't work
Pay.tsx
export const Pay = ():...
3
votes
1
answer
5k
views
Mock Linking.openURL in React Native it's never been called
I´m writing some tests for my app and I´m trying to mock Linking module. I'm using jest.
The Linking.canOpenURL mock it's working fine (toHaveBeenCalled is returning true), but openURL mock is never ...
3
votes
1
answer
3k
views
React Testing Library - testing hooks with React.context
I have question about react-testing-library with custom hooks
My tests seem to pass when I use context in custom hook, but when I update context value in hooks cleanup function and not pass.
So can ...
1
vote
1
answer
2k
views
Test custom hook with react-hooks-testing-library
I am trying to write tests for this custom hook using react-hooks-testing-library.
import { deleteArticleById } from '../../API/articles/deleteArticleById';
const useArticleDelete = () => {
const ...
1
vote
1
answer
4k
views
testing callback return value with react-hooks-testing-library
In this example we have a simple hook called useLog that returns a method. How do I test that it gets returned with react-hooks-testing-library. I am trying to figure out how to write the expect.
The ...
4
votes
1
answer
4k
views
result.current is null when using renderHook () Custom Hook to test custom hook in react-native using jest and testing-library
For My project I am using one custom hook for navigation some of my screens as from one screen to another screen based on the parameters provide to the function of custom hook. How could I Unit Test ...