I am trying to spy on useState React hook but i always get the test failed
This is my React component:
const Counter= () => {
const[counter, setCounter] = useState(0);
const handleClick=() => {
setCounter(counter + 1);
}
return (
<div>
<h2>{counter}</h2>
<button onClick={handleClick} id="button">increment</button>
</div>
)
}
counter.test.js:
it('increment counter correctlry', () => {
let wrapper = shallow(<Counter/>);
const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation((init) => [init, setState]);
const button = wrapper.find("button")
button.simulate('click');
expect(setState).toHaveBeenCalledWith(1);
})
Unfortunately this doesn't work and i get the test failed with that message:
expected 1
Number of calls: 0
diedu's answer led me the right direction and I came up with this solution:
Mock use state from react to return a jest.fn() as useState:
1.1 Also import useState immediately after - that will now be e jest mock (returned from the jest.fn() call)
jest.mock('react', ()=>({
...jest.requireActual('react'),
useState: jest.fn()
}))
import { useState } from 'react';
Later on in the beforeEach, set it to the original useState, for all the cases where you need it to not be mocked
describe("Test", ()=>{
beforeEach(()=>{
useState.mockImplementation(jest.requireActual('react').useState);
//other preperations
})
//tests
})
In the test itself mock it as needed:
it("Actual test", ()=>{
useState.mockImplementation(()=>["someMockedValue", someMockOrSpySetter])
})
Parting notes: While it might be conceptually somewhat wrong to get your hands dirty inside the "black box" one is unit testing, it is indeed super useful at times to do it.
You need to use React.useState instead of the single import useState.
I think is about how the code gets transpiled, as you can see in the babel repl the useState from the single import ends up being different from the one of the module import
_react.useState // useState
_react.default.useState // React.useState;
So you spy on _react.default.useState but your component uses _react.useState.
It seems impossible to spyOn a single import since you need the function to belong to an object, here is a very extensive guide that explains the ways of mocking/spying modules https://github.com/HugoDF/mock-spy-module-import
And as #Alex Mackay mentioned, you probably want to change your mindset about testing react components, moving to react-testing-library is recommended, but if you really need to stick to enzyme you don't need to go that far as to mock react library itself
Annoyingly Codesandbox is currently having trouble with its testing module so I can't post a working example but I will try to explain why mocking useState is generally a bad thing to do.
The user doesn't care if useState has been called, they care about when I click increment the count should increase by one therefore that is what you should be testing for.
// App
import React, { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
</div>
);
}
// Tests
import React from "react";
import App from "./App";
import { screen, render } from "#testing-library/react";
import userEvent from "#testing-library/user-event";
describe("App should", () => {
it('increment count value when "Increment" btn clicked', () => {
// Render the App
render(<App />);
// Get the count in the same way the user would, by looking for 'Count'
let count = screen.getByText(/count:/);
// As long as the h1 element contains a '0' this test will pass
expect(count).toContain(0);
// Once again get the button in the same the user would, by the 'Increment'
const button = screen.getByText(/increment/);
// Simulate the click event
userEvent.click(button);
// Refetch the count
count = screen.getByText(/count:/);
// The 'Count' should no longer contain a '0'
expect(count).not.toContain(0);
// The 'Count' should contain a '1'
expect(count).toContain(1);
});
// And so on...
it('reset count value when "Reset" btn is clicked', () => {});
it('decrement count value when "Decrement" btn is clicked', () => {});
});
Definitely check out #testing-library if you are interested in this style of testing. I switched from enzyme about 2 years ago and haven't touched it since.
just you need to import React in your test file like:
import * as React from 'react';
after that you can use the mock function.
import * as React from 'react';
:
:
it('increment counter correctlry', () => {
let wrapper = shallow(<Counter/>);
const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation((init) => [init, setState]);
const button = wrapper.find("button")
button.simulate('click');
expect(setState).toHaveBeenCalledWith(1);
})
you should use React.useState() instead useState(), But there are other ways...
in React you can set useState without React with this config
// setupTests.js
const { configure } = require('enzyme')
const Adapter = require('#wojtekmaj/enzyme-adapter-react-17')
const { createSerializer } = require('enzyme-to-json')
configure({ adapter: new Adapter() });
expect.addSnapshotSerializer(createSerializer({
ignoreDefaultProps: true,
mode: 'deep',
noKey: true,
}));
import React, { useState } from "react";
const Home = () => {
const [count, setCount] = useState(0);
return (
<section>
<h3>{count}</h3>
<span>
<button id="count-up" type="button" onClick={() => setCount(count + 1)}>Count Up</button>
<button id="count-down" type="button" onClick={() => setCount(count - 1)}>Count Down</button>
<button id="zero-count" type="button" onClick={() => setCount(0)}>Zero</button>
</span>
</section>
);
}
export default Home;
// index.test.js
import { mount } from 'enzyme';
import Home from '../';
import React, { useState as useStateMock } from 'react';
jest.mock('react', () => ({
...jest.requireActual('react'),
useState: jest.fn(),
}));
describe('<Home />', () => {
let wrapper;
const setState = jest.fn();
beforeEach(() => {
useStateMock.mockImplementation(init => [init, setState]);
wrapper = mount(<Home />);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('Count Up', () => {
it('calls setCount with count + 1', () => {
wrapper.find('#count-up').simulate('click');
expect(setState).toHaveBeenCalledWith(1);
});
});
describe('Count Down', () => {
it('calls setCount with count - 1', () => {
wrapper.find('#count-down').props().onClick();
expect(setState).toHaveBeenCalledWith(-1);
});
});
describe('Zero', () => {
it('calls setCount with 0', () => {
wrapper.find('#zero-count').props().onClick();
expect(setState).toHaveBeenCalledWith(0);
});
});
});
Related
The useEffect would run more than once for some reason (usually twice) and would print my message twice (or more). I have tried multiple solutions even with useMontainEffect but the result is always the same. Any solutions?
import './App.css';
import io from 'socket.io-client'
import { useEffect, useRef, useState } from 'react'
import React from 'react';
import ReactDOM from "react-dom/client";
const socket = io.connect("http://localhost:3001");
function App() {
const [message, setMessage] = useState("");
const [state, setState] = useState([]);
const [chat, setChat] = useState([]);
const socketRef = useRef();
const sendMessage = () => {
socket.emit("send_message", { message });
};
const renderChat = () => {
return (
chat.map(msg => {
return (
<h3>{msg.message['message']}</h3>
)
})
)
}
useEffect(() => {
socket.on("receive_message", message => {
setChat(prevState => [...prevState, {message}]);
});
}, [socket])
return (
<div className="App">
<input placeholder="Message..." onChange={(event) => {
setMessage(event.target.value);}}
/>
<button onClick={sendMessage}>Send Message</button>
<h1>Message:</h1>
{renderChat()}
</div>
);
}
export default App;
In strict mode the component will be mounted, unmounted, then re-mounted. You can add a cleanup function. The double invocation however is expected.
useEffect(() => {
const listener = message => {
setChat(prevState => [...prevState, {message}]);
};
socket.on("receive_message", listener);
return () => socket.off('receive_message', listener);
}, [socket])
If u want to check, U can turn off the strict mode and check exactly how many times the useEffect call back function runs
Note : but don't always turn off the strict mode because
--> strict mode is actually because if we forgot any cleanup function in useEffect , ui behaves differently
--> with that only we came to know that we did something mistake
--> strict mode is present in only development mode, it won't be in production mode
I am trying to implement a search that makes a new query on each character change. After n milliseconds, I need to make a change to the object that stores some properties.
//user typing
const onInputChange = (e) => {
let searchInput = e.target.value;
useDebounce(
handleSearchPropsChange({
filter: {
searchInput,
dateRange: {
start,
end
}
}
}), 1000
);
}
The function I am using for the delayed call
import {debounce} from 'lodash';
import {useRef} from 'react';
export function useDebounce(callback = () => {}, time = 500) {
return useRef(debounce(callback, time)).current;
}
But I am getting the error:
Invalid hook call. Hooks can only be called inside of the body of a function component. This
could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
A example without lodash, just Hooks.
UseDebounce.js
import { useEffect, useCallback } from 'react';
export default function useDebounce(effect, dependencies, delay) {
const callback = useCallback(effect, dependencies);
useEffect(() => {
const timeout = setTimeout(callback, delay);
return () => clearTimeout(timeout);
}, [callback, delay]);
}
App.js
import React, { useState } from 'react';
import useDebounce from './useDebounce';
import data from './data';
export default function App() {
const [search, setSearch] = useState('');
const [filteredTitle, setFilteredTitle] = useState([]);
// DeBounce Function
useDebounce(() => {
setFilteredTitle(
data.filter((d) => d.title.toLowerCase().includes(search.toLowerCase()))
);
}, [data, search], 800
);
const handleSearch = (e) => setSearch(e.target.value);
return (
<>
<input
id="search"
type="text"
spellCheck="false"
placeholder="Search a Title"
value={search || ''}
onChange={handleSearch}
/>
<div>
{filteredTitle.map((f) => (
<p key={f.id}>{f.title}</p>
))}
</div>
</>
);
}
Demo : Stackblitz
I'm trying to figure out if there is a way to prevent the "not wrapped in act(...)" warning thrown by Jest/testing-library when I have nothing to assert after the state update that causes the warning happens, or if I should just ignore this warning.
Suppose I have this simple component:
import React, {useEffect, useState} from 'react';
import {getData} from 'services';
const MyComponent = () => {
const [arr, setArr] = useState([]);
useEffect(() => {
(async () => {
const {items} = await getData();
setArr(items);
})();
}, []);
return (
<div>
{!(arr.length > 0) && <p>no array items</p>}
{arr.length > 0 && (
<ul>
{arr.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
};
export default MyComponent;
Suppose I want to simply test that this component renders okay even if getData() doesn't return any data for me.
So I have a test like this:
import React from 'react';
import {getData} from 'services';
import {render, screen} from 'testUtils';
import MyComponent from './MyComponent';
jest.mock('services', () => ({
getData: jest.fn(),
}));
it('renders', () => {
getData.mockResolvedValue({items: []});
render(<MyComponent />);
expect(screen.getByText('no array items')).toBeInTheDocument();
});
This test will pass, but I'll get the "not wrapped in act(...)" warning because the test will finish before getData() has a chance to finish.
In this case, the response from getData() sets arr to the same value (an empty array) as I have initially set it to at the top of the component. As such, my UI doesn't change after the async function completes—I'm still just looking at a paragraph that says "no array items"—so I don't really have anything I can assert that would wait for the state update to complete.
I can expect(getData).toHaveBeenCalledTimes(1), but that doesn't wait for the state to actually be updated after the function call.
I have attempted an arbitrary pause in the test to allow time for setArr(items) to happen:
it('renders', async () => {
getData.mockResolvedValue({items: []});
render(<MyComponent />);
expect(screen.getByText('no array items')).toBeInTheDocument();
await new Promise(resolve => setTimeout(resolve, 2000));
expect(screen.getByText('no array items')).toBeInTheDocument();
});
But that doesn't seem to help, and I'm honestly not sure why.
Is there a way to handle this situation by modifying only the test?
I am sure I could fix the problem by refactoring MyComponent, e.g., by passing arr to MyComponent as a prop and moving the getData() call to a parent component, or creating some custom prop used only for testing that would skip the getData() call altogether, but I don't want to be modifying components purely to avoid warnings in tests.
I am using testing-library/react, v11.2.2.
You can use findByText (a combination of getByText and waitFor) to ensure all updates have happened when the assertion resolves.
it('renders', async () => {
getData.mockResolvedValue({items: []});
render(<MyComponent />);
expect(await screen.findByText('no array items')).toBeInTheDocument();
});
#juliomalves's answer is spot on.
However, I had to put this await in my beforeEach:
import {render, fireEvent} from '#testing-library/react';
import MyComponent from './MyComponent';
...
describe('MyComponent should', () => {
let getByText, getByTestId, getAllByTestId, getByLabelText;
beforeEach(async () => {
let findByText;
({
getByText,
getByTestId,
getAllByTestId,
getByLabelText,
findByText,
} = render(<MyComponent {...props} />));
// Have this here to avoid warnings because of setting state variables
await findByText('no array items');
})
...
});
I have got code for usePrevious hook from somewhere on internet. The code for usePrevious looks like:
export const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
Now, I am learing testing react with jest and enzyme. So, I tried to test usePrevious and got some problems. Here is my test case:
import React from 'react';
import { render } from 'enzyme';
import { usePrevious } from './customHooks';
const Component = ({ children, value }) => children(usePrevious(value));
const setup = (value) => {
let returnVal = '';
render(
<Component value={value}>
{
(val) => {
returnVal = val;
return null;
}
}
</Component>,
);
return returnVal;
};
describe('usePrevious', () => {
it('returns something', () => {
const test1 = setup('test');
const test2 = setup(test1);
expect(test2).toBe('test');
});
});
When the test execution completes, I get this error:
Expected: 'test', Received: undefined
Can anyone please let me know why am I getting undefined and is this the correct way to test custom hoooks in react?
After suggestion from comments from #Dmitrii G, I have changed my code to re-render the component (Previously I was re-mounting the component).
Here is the updated code:
import React from 'react';
import PropTypes from 'prop-types';
import { shallow } from 'enzyme';
import { usePrevious } from './customHooks';
const Component = ({ value }) => {
const hookResult = usePrevious(value);
return (
<div>
<span>{hookResult}</span>
<span>{value}</span>
</div>
);
};
Component.propTypes = {
value: PropTypes.string,
};
Component.defaultProps = {
value: '',
};
describe('usePrevious', () => {
it('returns something', () => {
const wrapper = shallow(<Component value="test" />);
console.log('>>>>> first time', wrapper.find('div').childAt(1).text());
expect(wrapper.find('div').childAt(0).text()).toBe('');
// Test second render and effect
wrapper.setProps({ value: 'test2' });
console.log('>>>>> second time', wrapper.find('div').childAt(1).text());
expect(wrapper.find('div').childAt(0).text()).toBe('test');
});
});
But still I am getting the same error
Expected: "test", Received: ""
Tests Passes when settimeout is introduced:
import React from 'react';
import PropTypes from 'prop-types';
import { shallow } from 'enzyme';
import { usePrevious } from './customHooks';
const Component = ({ value }) => {
const hookResult = usePrevious(value);
return <span>{hookResult}</span>;
};
Component.propTypes = {
value: PropTypes.string,
};
Component.defaultProps = {
value: '',
};
describe('usePrevious', () => {
it('returns empty string when component is rendered first time', () => {
const wrapper = shallow(<Component value="test" />);
setTimeout(() => {
expect(wrapper.find('span').text()).toBe('');
}, 0);
});
it('returns previous value when component is re-rendered', () => {
const wrapper = shallow(<Component value="test" />);
wrapper.setProps({ value: 'test2' });
setTimeout(() => {
expect(wrapper.find('span').text()).toBe('test');
}, 0);
});
});
I am not a big fan of using settimeout, so I feel that probably i am doing some mistake. If anyone knows a solution that does not use settimeout, feel free to post here. Thank you.
Enzyme by the hood utilizes React's shallow renderer. And it has issue with running effects. Not sure if it's going to be fixed soon.
Workaround with setTimeout was a surprise to me, did not know it works. Unfortunately, it is not universal approach since you'd need to use that on any change that cases re-render. Really fragile.
As a solution you can use mount() instead.
Also you may mimic shallow rendering with mount() with mocking every nested component:
jest.mock("../MySomeComponent.jsx", () =>
(props) => <span {...props}></span>
);
I'm trying to create simple refresher component here
Refresher.js
import { useEffect } from 'react';
const Refresher = ({ onRefresh }) => {
useEffect(() => {
const id = setInterval(onRefresh, 60000);
return () => {
clearInterval(id);
};
}, [onRefresh]);
return null;
};
export default Refresher;
However, when i try to test it using jest.useFakeTimers(), somehow it's didn't work. The stub is not called even after jest.runOnlyPendingTimers()
import React from 'react';
import renderer from 'react-test-renderer';
import Refresher from '../Refresher';
describe('Refresher', () => {
test('should refresh the result every 60 seconds', () => {
jest.useFakeTimers();
const onRefreshSpy = jest.fn();
const refresher = renderer.create(<Refresher onRefresh={onRefreshSpy} />);
expect(onRefreshSpy).not.toHaveBeenCalled();
jest.runOnlyPendingTimers();
refresher.update(); // Trying force update here
expect(onRefreshSpy).toHaveBeenCalled();
});
});
If not mistaken, the interval will not run if the component are not update, so i tried to use refresher.update(), but seems like it's not really work.
Anyone know how to fix the test here?
You just need to mock useLayoutEffect instead of useEffect. See issue here
describe('Refresher', () => {
beforeAll(() => jest.spyOn(React, 'useEffect').mockImplementation(React.useLayoutEffect))
test('should refresh the result every 60 seconds', () => {
jest.useFakeTimers();
const onRefreshSpy = jest.fn();
const refresher = renderer.create(<Refresher onRefresh={onRefreshSpy} />);
expect(onRefreshSpy).not.toHaveBeenCalled();
jest.runOnlyPendingTimers();
expect(onRefreshSpy).toHaveBeenCalled();
});
});
You have better control with the modern fake timers.
import React from 'react';
import renderer from 'react-test-renderer';
import Refresher from '../Refresher';
describe('Refresher', () => {
test('should refresh the result every 60 seconds', () => {
jest.useFakeTimers('modern'); // default for Jest 27+
const onRefreshSpy = jest.fn();
const refresher = renderer.create(<Refresher onRefresh={onRefreshSpy} />);
expect(onRefreshSpy).not.toHaveBeenCalled();
jest.advanceTimersByTime(60000);
expect(onRefreshSpy).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(60000);
expect(onRefreshSpy).toHaveBeenCalledTimes(2);
});
});