React test onChange on input using react shallow-renderer - reactjs

I'm trying to test searchForm component of React with onChange prop.
const SearchForm = () => {
const [value, setValue] = useState('');
return (
<form className={styles.searchForm}>
<input
value={value}
onChange={(e) => setValue(e.target.value)} // test this line
className={styles.searchForm__input}
/>
<button type="submit" aria-label="Search" className={styles.searchForm__button} />
</form>
);
};
Here is example of my test:
import React from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
import SearchForm from '../index';
const setUp = () => {
const renderer = new ShallowRenderer();
renderer.render(<SearchForm />);
return renderer.getRenderOutput();
};
describe('render form component', () => {
it('handle onChange in form input field', () => {
const result = setUp();
expect(result).toMatchSnapshot();
});
});
This test passes, but JEST says that this line of code (with onChange) is uncovered.
I found how to launch onChange:
result.props.children[0].props.onChange();
This launches original prop but i get error on e.target -- cannot read property of undefined.
I feel like i need to mock setValue somehow, but i can't figure out how. I'm new to JEST.
Maybe this may be done with just react-test-renderer in better way.

Here is the solution:
index.tsx:
import React, { useState } from 'react';
export const SearchForm = () => {
const [value, setValue] = useState('');
return (
<form>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<button type="submit" aria-label="Search" />
</form>
);
};
index.test.tsx:
import React from 'react';
import TestRenderer, { act } from 'react-test-renderer';
import ShallowRenderer from 'react-test-renderer/shallow';
import { SearchForm } from './';
describe('66907704', () => {
it('should handle onChange event', () => {
const testRenderer = TestRenderer.create(<SearchForm />);
const testInstance = testRenderer.root;
expect(testInstance.findByType('input').props.value).toEqual('');
const mEvent = { target: { value: 'teresa teng' } };
act(() => {
testInstance.findByType('input').props.onChange(mEvent);
});
expect(testInstance.findByType('input').props.value).toEqual('teresa teng');
});
it('should handle onChange event when use shallow render', () => {
const shallowRenderer = ShallowRenderer.createRenderer();
shallowRenderer.render(<SearchForm />);
let tree = shallowRenderer.getRenderOutput();
let input = tree.props.children[0];
const mEvent = { target: { value: 'teresa teng' } };
input.props.onChange(mEvent);
tree = shallowRenderer.getRenderOutput();
input = tree.props.children[0];
expect(input.props.value).toEqual('teresa teng');
});
});
unit test result:
PASS examples/66907704/index.test.tsx (6.636 s)
66907704
✓ should handle onChange event (10 ms)
✓ should handle onChange event when use shallow render (1 ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 7.443 s
package versions:
"jest": "^26.6.3",
"react": "^16.14.0",

Related

Simulate change on input does not call a function

I learning to write unit tests in React. The test should check if an onChange function is called when there is a change in the input field. This is my simple search bar component:
import {Input} from './Input';
const SearchBar = (props) => {
return (
<Input
type="search"
data-test="search"
onChange={e => props.onSearch(e.target.value)} />
);
};
export default SearchBar;
The test I wrote is supposed to simulate a change on input field, what in turn should invoke a function call.
describe('Search', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('Should call onSearch function', () => {
const wrapper = mount(<SearchBar onSearch={onSearch}/>);
const searchBar = wrapper.find('[data-test=search]').at(0);
searchBar.simulate('change', {target: { 'test' }});
expect(onSearch).toBeCalledTimes(1);
});
});
Here, instead of being called 1 time, the function is not called at all. I cannot figure out why. Can you explain where am I making a mistake?
You should create a mocked onSearch using jest.fn(). The CSS selector should be '[data-test="search"]'.
E.g.
SearchBar.tsx:
import React from 'react';
function Input(props) {
return <input {...props} />;
}
const SearchBar = (props) => {
return <Input type="search" data-test="search" onChange={(e) => props.onSearch(e.target.value)} />;
};
export default SearchBar;
SearchBar.test.tsx:
import { mount } from 'enzyme';
import React from 'react';
import SearchBar from './SearchBar';
describe('Search', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('Should call onSearch function', () => {
const onSearch = jest.fn();
const wrapper = mount(<SearchBar onSearch={onSearch} />);
const searchBar = wrapper.find('[data-test="search"]').at(0);
searchBar.simulate('change', { target: { value: 'test' } });
expect(onSearch).toBeCalledTimes(1);
});
});
test result:
PASS examples/68669299/SearchBar.test.tsx (7.33 s)
Search
✓ Should call onSearch function (47 ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
SearchBar.tsx | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.002 s, estimated 9 s

How to mock and test scrollBy with Jest and React-Testing-Library?

Given the following component:
import * as React from "react";
import "./styles.css";
export default function App() {
const scrollContainerRef = React.useRef<HTMLDivElement | null>(null);
const handleClick = () => {
scrollContainerRef?.current?.scrollBy({ top: 0, left: 100 });
};
return (
<div aria-label="wrapper" ref={scrollContainerRef}>
<button onClick={handleClick}>click</button>
</div>
);
}
How do I write a test using Jest and React Testing library to check that when the button is clicked, scrollBy is triggered on the wrapper?
I have tried the following and it doesn't seem to be working:
test('Clicking on button should trigger scroll',() => {
const myMock = jest.fn();
Object.defineProperty(HTMLElement.prototype, 'scrollBy', {
configurable: true,
value: myMock(),
})
render(<MyComponent />)
fireEvent.click(screen.getByText(/click/i))
expect(myMock).toHaveBeenCalledWith({top: 0, left: 100})
})
Since jsdom does NOT implements Element.scrollBy() method, see PR. We can create a mocked ref object with getter and setter to intercept React's assignment process to ref.current, and install spy or add mock in the process.
E.g.
App.tsx:
import * as React from 'react';
export default function App() {
const scrollContainerRef = React.useRef<HTMLDivElement | null>(null);
const handleClick = () => {
scrollContainerRef?.current?.scrollBy({ top: 0, left: 100 });
};
return (
<div aria-label="wrapper" ref={scrollContainerRef}>
<button onClick={handleClick}>click</button>
</div>
);
}
App.test.tsx:
import React, { useRef } from 'react';
import { render, screen, fireEvent } from '#testing-library/react';
import { mocked } from 'ts-jest/utils';
import App from './App';
jest.mock('react', () => {
return {
...jest.requireActual<typeof React>('react'),
useRef: jest.fn(),
};
});
const useMockRef = mocked(useRef);
describe('63702104', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('should pass', () => {
const ref = { current: {} };
const mScrollBy = jest.fn();
Object.defineProperty(ref, 'current', {
set(_current) {
if (_current) {
_current.scrollBy = mScrollBy;
}
this._current = _current;
},
get() {
return this._current;
},
});
useMockRef.mockReturnValueOnce(ref);
render(<App />);
fireEvent.click(screen.getByText(/click/i));
expect(mScrollBy).toBeCalledWith({ top: 0, left: 100 });
});
});
test result:
PASS examples/63702104/App.test.tsx (9.436 s)
63702104
✓ should pass (33 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 75 | 100 | 100 |
App.tsx | 100 | 75 | 100 | 100 | 7
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.21 s

React hooks not setting state while testing using jest

I have a react component
const Upload = (props) => {
const [fileName, setFileName] = useState("no file chosen")
function handleFile(e) {
const [sFile] = e.target.files;
setFileName(sFile.name);
}
const chooseFile = (
<label>
<input id="file-upload" type="file" accept=".pdf, application/pdf" onChange={handleFile} />
choose_file
</label>
<label className='file-text'>
{fileName}
</label>
);
return (
<React.Fragment>
{chooseFile}
</React.Fragment>
);
};
I have this test for checking the value change of state fileName, so that it displays the name of the file chosen
beforeEach(() => {
wrapper = shallow(<Upload />);
});
describe('Choose File', () => {
const mockedFile = 'application.pdf';
const event = {
target: {
files: [{ name: 'application.pdf' }]
}
};
it('displays the file name when a file is selected', () => {
wrapper.find('#file-upload').simulate('change', event);
wrapper.update();
expect(wrapper.find('label').at(1).text()).toEqual(mockedFile);
});
}
But the output is always "no file chosen". Any help would be appreciated.
Your code works fine for me.
index.tsx:
import React, { useState } from 'react';
export const Upload = props => {
const [fileName, setFileName] = useState('no file chosen');
function handleFile(e) {
const [sFile] = e.target.files;
setFileName(sFile.name);
}
return (
<React.Fragment>
<label>
<input id="file-upload" type="file" accept=".pdf, application/pdf" onChange={handleFile} />
choose_file
</label>
<label className="file-text">{fileName}</label>
</React.Fragment>
);
};
index.spec.tsx:
import React from 'react';
import { shallow } from 'enzyme';
import { Upload } from './';
let wrapper;
beforeEach(() => {
wrapper = shallow(<Upload />);
});
describe('Choose File', () => {
const mockedFile = 'application.pdf';
const event = {
target: {
files: [{ name: 'application.pdf' }]
}
};
it('displays the file name when a file is selected', () => {
wrapper.find('#file-upload').simulate('change', event);
wrapper.update();
expect(
wrapper
.find('label')
.at(1)
.text()
).toEqual(mockedFile);
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/58793061/index.spec.tsx
Choose File
✓ displays the file name when a file is selected (12ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.924s
dependencies versions:
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"jest": "^24.9.0",
"jest-environment-enzyme": "^7.1.1",
"jest-enzyme": "^7.1.1",
"react": "^16.11.0",
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58793061

After Simulate('change') state is not updated

I've got a search filter component with an input inside it, and it's connected to redux.
class SearchFilter extends PureComponent {
constructor (props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
keyword: props.searchKeyword
};
}
handleInputChange (e) {
this.setState({keyword: e.target.value});
this.props.dispatch(SetFiltersValue(...);
}
render () {
const {keyword} = this.state;
return (
<div className="search-w bp3-input-group">
<span className="bp3-icon bp3-icon-search"/>
<input className="bp3-input" value={keyword} type="text" placeholder="Search input" dir="auto" onChange={this.handleInputChange} />
</div>
);
}
}
const mapStateToProps = (_, ownParams) => {...};
export default connect(mapStateToProps)(SearchFilter);
I wrote a test in jest and enzyme to test state updates when user enters a new value
import React from "react";
import SearchFilter from "../../dev/components/shared/searchFilter";
import {shallow, mount} from "enzyme";
import configureStore from "redux-mock-store";
describe("Testing Search filter", () => {
const mockStore = configureStore(),
initialStoreState = {
filtersParams: {}
};
let store;
beforeEach(() => {
store = mockStore(initialStoreState);
});
it("Update search field value when user enters a value", () => {
const wrapper = shallow(<SearchFilter store={store}/>).dive(),
searchInput = wrapper.find("input.bp3-input").first();
expect(searchInput).toBeDefined();
const mockedEvent = {
preventDefault () {},
target: { value: "foo" }
};
expect(wrapper.state("keyword")).toEqual("");
searchInput.simulate("change", mockedEvent);
wrapper.update();
expect(wrapper.state("keyword")).toEqual("foo");
});
});
The problem is that state does't update after simulating change, and test always fails.
How can I fix this or is there other way to test state updates?
Comment is cheap, show you the code:
index.tsx, the React Component to be tested:
import React, { PureComponent } from 'react';
import { connect, DispatchProp } from 'react-redux';
import { SetFiltersValue } from './actionCreators';
interface ISearchFilterStateProps {
searchKeyword: string;
}
interface ISearchFilterState {
keyword: string;
}
type Props = ISearchFilterStateProps & DispatchProp;
class SearchFilter extends PureComponent<Props, ISearchFilterState> {
constructor(props: Props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
keyword: props.searchKeyword
};
}
public handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
this.setState({ keyword: e.target.value });
this.props.dispatch(SetFiltersValue());
}
public render() {
const { keyword } = this.state;
return (
<div className="search-w bp3-input-group">
<span className="bp3-icon bp3-icon-search" />
<input
className="bp3-input"
value={keyword}
type="text"
placeholder="Search input"
dir="auto"
onChange={this.handleInputChange}
/>
</div>
);
}
}
const mapStateToProps = (_, ownParams) => {
return { searchKeyword: '' };
};
export default connect(mapStateToProps)(SearchFilter);
actionCreators.ts:
export const SetFiltersValue = () => ({ type: 'SET_FILTER' });
Unit test:
import React from 'react';
import { shallow } from 'enzyme';
import configureStore from 'redux-mock-store';
import SearchFilter from './';
import { SetFiltersValue } from './actionCreators';
const initialState = { filtersParams: {} };
type State = typeof initialState;
const mockStore = configureStore<State>();
describe('SearchFilter', () => {
let store;
beforeEach(() => {
store = mockStore(initialState);
});
it('t1', () => {
const searchFilter = shallow(<SearchFilter store={store}></SearchFilter>).dive();
const searchInputWrapper = searchFilter.dive();
const searchInput = searchInputWrapper.find('input.bp3-input').first();
expect(searchInputWrapper.state('keyword')).toBe('');
const mockedEvent = {
preventDefault: jest.fn(),
target: { value: 'foo' }
};
searchInput.simulate('change', mockedEvent);
expect(searchInputWrapper.state('keyword')).toBe('foo');
expect(store.getActions()).toEqual([SetFiltersValue()]);
expect(searchInputWrapper.html()).toMatchSnapshot();
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/54587960/index.spec.tsx
SearchFilter
✓ t1 (28ms)
› 1 snapshot written.
-------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
actionCreators.ts | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-------------------|----------|----------|----------|----------|-------------------|
Snapshot Summary
› 1 snapshot written from 1 test suite.
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 1 written, 1 total
Time: 4.367s, estimated 5s
React Component Snapshot:
// Jest Snapshot v1
exports[`SearchFilter t1 1`] = `"<div class=\\"search-w bp3-input-group\\"><span class=\\"bp3-icon bp3-icon-search\\"></span><input type=\\"text\\" class=\\"bp3-input\\" value=\\"foo\\" placeholder=\\"Search input\\" dir=\\"auto\\"/></div>"`;
Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54587960

Failed React Jest Test when Expecting Mock Function to be called

Okay i've uploaded an even more straight forward example. I just can't get mock functions to be called when they are located inside of a helper function. Not sure what i'm doing wrong.
class TodoSearch extends Component {
handleSearch = () => {
const searchInput = this.searchInput.value;
// passed down from parent component
this.props.onSearch(searchInput);
};
handleCheckbox = e => {
const showCompleted = e.target.checked;
// passed down from parent component
this.props.onCheckbox(showCompleted);
};
render() {
return (
<form>
<FormGroup>
<FormControl
type="search"
className="todoSearchInput"
placeholder="Search"
inputRef={input => (this.searchInput = input)}
onChange={this.handleSearch}
/>
<Checkbox checked={this.props.checked} onChange={this.handleCheckbox}>
Show completed todos
</Checkbox>
</FormGroup>
</form>
);
}
}
export default TodoSearch;
So i'm using Jest and Enzyme as thus, the 'shallow'. This is what i've successful done so far
import React from 'react';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer';
import TodoSearch from './TodoSearch';
describe(TodoSearch, () => {
const searchText = 'Buy Milk';
const mockOnSearch = jest.fn();
const component = shallow(<TodoSearch onSearch={mockOnSearch} />);
it('should exist', () => {
const component = renderer.create(<TodoSearch />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('contains the form', () => {
expect(component.find('form')).toHaveLength(1);
expect(component.find('Checkbox')).toHaveLength(1);
expect(component.find('.todoSearchInput')).toHaveLength(1);
});
});
How can i test that onSearch inside the handleSearch is run? Tried a bunch of ways but just not getting it. Any help greatly appreciated.
Here is the solution, I simplify your component, remove the unrelated part.
dependencies:
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
"jest": "^24.8.0",
"react": "^16.9.0",
TodoSearch.tsx:
import React, { Component } from 'react';
import console = require('console');
interface ITodoSearchProps {
onSearch(input): any;
onCheckbox(value): any;
}
class TodoSearch extends Component<ITodoSearchProps> {
private searchInput: HTMLInputElement | null = null;
constructor(props: ITodoSearchProps) {
super(props);
}
public handleSearch = () => {
if (this.searchInput) {
const searchInput = this.searchInput.value;
console.log('searchInput: ', searchInput);
// passed down from parent component
this.props.onSearch(searchInput);
}
}
public handleCheckbox = e => {
const showCompleted = e.target.checked;
// passed down from parent component
this.props.onCheckbox(showCompleted);
}
public render() {
return (
<form>
<input
type="search"
className="todoSearchInput"
placeholder="Search"
onChange={this.handleSearch}
ref={input => (this.searchInput = input)}
/>
</form>
);
}
}
export default TodoSearch;
TodoSearch.spec.tsx:
import React from 'react';
import TodoSearch from './TodoSearch';
import { mount } from 'enzyme';
describe('TodoSearch', () => {
const mockOnSearch = jest.fn();
const mockOnCheckbox = jest.fn();
it('should handle search correctly', () => {
const searchInput = 'jest';
const wrapper = mount(<TodoSearch onSearch={mockOnSearch} onCheckbox={mockOnCheckbox}></TodoSearch>);
(wrapper.find('input').instance() as any).value = searchInput;
wrapper.find('input').simulate('change');
expect(mockOnSearch).toBeCalledWith(searchInput);
});
});
Unit test result with coverage report:
PASS src/stackoverflow/47493126/TodoSearch.spec.tsx
TodoSearch
✓ should handle search correctly (50ms)
searchInput: jest
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 90 | 75 | 83.33 | 88.89 | |
TodoSearch.tsx | 90 | 75 | 83.33 | 88.89 | 24,26 |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.846s, estimated 6s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/47493126

Resources