I need to mutate React child component's prop which receives parents' function.
After updating the wrapper's function it changes but not affect to child component
// Component
import React from 'react';
export default class Component extends React.Component {
clickFunction() {
console.log("Parent's Click fn");
}
render() {
return (
<div>
<Button onClick={this.clickFunction} data-test-id="button" />
</div>
);
}
}
// Test
import React from 'react';
import {shallow} from 'enzyme';
const mockClickFunction = jest.fn(() => console.log('Mock Click fn'));
describe('Test Component', () => {
it('Should mutate child prop', () => {
const wrapper = shallow(<Component />);
wrapper.find('[data-test-id="button"]').simulate('click') // Parent's Click fn
console.log(wrapper.instance().clickFunction) // [Function: bound clickFunction]
wrapper.instance().clickFunction = mockClickFunction;
wrapper.update();
console.log(wrapper.instance().clickFunction) // [Function: mockConstructor]
wrapper.find('[data-test-id="button"]').simulate('click') // Parent's Click fn but should be Mock Click fn
})
})
How I can change child Component onClick function?
A reference to the original clickFunction has been used in the render. You can't mock it by overriding it after the component is already shallow-rendered.
Try spying on Component.prototype.clickFunction before calling shallow.
E.g.
index.jsx:
import React from 'react';
export default class Component extends React.Component {
clickFunction() {
console.log("Parent's Click fn");
}
render() {
return (
<div>
<button onClick={this.clickFunction} data-test-id="button" />
</div>
);
}
}
index.test.tsx:
import { shallow } from 'enzyme';
import React from 'react';
import Component from '.';
describe('55611882', () => {
it('should pass', () => {
const mockClickFunction = jest
.spyOn(Component.prototype, 'clickFunction')
.mockImplementation(() => console.log('Mock Click fn'));
const wrapper = shallow(<Component />);
wrapper.find('[data-test-id="button"]').simulate('click');
expect(mockClickFunction).toBeCalledTimes(1);
mockClickFunction.mockRestore();
});
});
test result:
PASS examples/55611882/index.test.jsx (13.099 s)
55611882
✓ should pass (81 ms)
console.log
Mock Click fn
at examples/55611882/index.test.jsx:9:41
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 75 | 100 | 50 | 75 |
index.jsx | 75 | 100 | 50 | 75 | 5
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.416 s
Related
Let's say I have a component like so:
export function Click(props: { counter: number }) {
const [ counter, setCounter ] = useState(props.counter);
return (
<header className="App-header">
<h1 data-test="counter">{counter}</h1>
<button onClick={() => setCounter(counter + 1)}>
Click me
</button>
</header>
);
}
And my test file is like so:
import React from 'react';
import { mount } from "enzyme";
import App, { Click } from './App';
class Setup<Props> {
constructor(FunctionComponent: React.FC<Props>, props: Props) {
return mount(
<>
{FunctionComponent(props)}
</>
)
}
}
test("Doesn't work", () => {
const wrapper = new Setup(Click, { counter: 0 });
expect(wrapper.find(`[data-test="counter"]`)).toHaveLength(1);
});
This returns an error:
Hooks can only be called inside of the body of a function component.
But I don't really know how to solve it.
You see, I can't use a Functional Component because it would ruin the purpose.
My idea is to create a library to help me write tests, so I'd like to use classes.
To be a component function returning JSX should be used as <Component /> and not as Component().
hooks-rules doc says:
Don’t call Hooks inside loops, conditions, or nested functions.
Don’t call Hooks from regular JavaScript functions.
Don't call them, render them.
E.g.
App.tsx:
import React from 'react';
import { useState } from 'react';
export function Click(props: { counter: number }) {
const [counter, setCounter] = useState(props.counter);
return (
<header className="App-header">
<h1 data-test="counter">{counter}</h1>
<button onClick={() => setCounter(counter + 1)}>Click me</button>
</header>
);
}
App.test.tsx:
import React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import { Click } from './App';
class Setup<Props> {
constructor(FunctionComponent: React.FC<Props>, props: Props) {
return mount(<FunctionComponent {...props} />);
}
}
describe('68201330', () => {
test('it should pass', () => {
const wrapper = new Setup(Click, { counter: 0 }) as ReactWrapper;
expect(wrapper.find(`[data-test="counter"]`)).toHaveLength(1);
});
});
test result:
PASS examples/68201330/App.test.tsx (8.477 s)
68201330
✓ it should pass (31 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 83.33 | 100 | 50 | 83.33 |
App.tsx | 83.33 | 100 | 50 | 83.33 | 11
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.331 s, estimated 10 s
I want to test that a class method is called on 'mousedown' event. Please take a look on the code below.
This is my component:
import React, { Component } from 'react';
import styled from 'styled-components';
import MyChildClass from './MyChildClass';
export default class MyClass extends Component {
constructor(props) {
super(props);
// Init state
this.state = {
balls: []
};
this.onMouseUpHandler = this.onMouseUpHandler.bind(this, this.state.balls);
}
onMouseDownHandler = (balls, e) => {
...
};
render() {
return (
<StyledEnvironment className='wrapper'>
<div
onMouseDown={this.onMouseDownHandler}
onMouseUp={this.onMouseUpHandler}
>
{balls}
</div>
</StyledEnvironment>
);
}
And this is my test:
import React from 'react';
import { mount, shallow } from 'enzyme';
import MyClass from '../MyClass';
it('should call onMouseDownHandler on mouse down', () => {
//...arrange
const instance = component.instance();
const wrapper = component.find('.wrapper').at(0);
instance.setMousePosition = jest.fn();
instance.onMouseDownHandler = jest.fn();
instance.forceUpdate();
component.update();
//...act
wrapper.simulate('mouseDown');
//...assert
expect(instance.onMouseDownHandler).toHaveBeenCalled();
});
So, I eventually expect the test to pass, but still the runner returns fail, with message
Expected mock function to have been called, but it was not called.
I've gone through many examples on Google, and found out that this is proper pattern of testing events.
Use arrow function as the method of class is not easy to test. Because it will be used as property of class, not instance method of class. So I suggest you refactor the method.
After refactoring, you can use jest.spyOn(object, methodName) to spy on the onMouseDownHandler method.
For example,
index.tsx:
import React, { Component } from 'react';
const StyledEnvironment = ({ children, className }) => <div className={className}>{children}</div>;
export default class MyClass extends Component<any, any> {
constructor(props) {
super(props);
this.state = {
balls: []
};
}
onMouseDownHandler(balls, e) {
// TBD
}
onMouseUpHandler(balls, e) {
// TBD
}
render() {
return (
<StyledEnvironment className="wrapper">
<div
onMouseDown={e => this.onMouseDownHandler(this.state.balls, e)}
onMouseUp={e => this.onMouseUpHandler(this.state.balls, e)}>
{this.state.balls}
</div>
</StyledEnvironment>
);
}
}
index.spec.tsx:
import React from 'react';
import { shallow } from 'enzyme';
import MyClass from './';
describe('MyClass', () => {
test('should handle mousedown event', () => {
const wrapper = shallow(<MyClass></MyClass>);
const onMouseDownHandlerSpy = jest.spyOn(MyClass.prototype, 'onMouseDownHandler');
wrapper.find('div').simulate('mouseDown');
expect(onMouseDownHandlerSpy).toBeCalled();
});
});
Unit test result with coverage report:
PASS src/stackoverflow/58652312/index.spec.tsx
MyClass
✓ should handle mousedown event (12ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 76.47 | 100 | 62.5 | 91.67 | |
index.tsx | 76.47 | 100 | 62.5 | 91.67 | 25 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.951s, estimated 9s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58652312
I need to test a React Client app using SocketIO Client. I have searched various websites online but couldn't get any of their examples to work. I then installed Express on the client app as a dev dependency and tried to start a test server in the Jest test but couldn't get that to work.
So I was wondering, in fact, what would be the right way to test this app anyway?
My target is to test the following event listener registered in componentDidMount
componentDidMount() {
const current_this = this;
socket.on("numOfPlayersChanged", function(data) {
// do something
});
}
Here is my solution:
index.tsx:
import React, { Component } from 'react';
import io from 'socket.io';
const socket = io();
class SomeComponent extends Component {
constructor(props) {
super(props);
this.handleNumOfPlayersChanged = this.handleNumOfPlayersChanged.bind(this);
}
componentDidMount() {
socket.on('numOfPlayersChanged', this.handleNumOfPlayersChanged);
}
render() {
return <div>some component</div>;
}
handleNumOfPlayersChanged() {
console.log('do something');
}
}
export default SomeComponent;
index.spec.tsx:
import React from 'react';
import SomeComponent from './';
import { shallow } from 'enzyme';
import io from 'socket.io';
jest.mock('socket.io', () => {
const mSocket = {
on: jest.fn()
};
return jest.fn(() => mSocket);
});
describe('SomeComponent', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<SomeComponent></SomeComponent>);
jest.restoreAllMocks();
});
test('should mount component and register socket event', () => {
const instance = wrapper.instance() as any;
const mSocket = io();
expect(wrapper.text()).toBe('some component');
expect(mSocket.on).toBeCalledWith('numOfPlayersChanged', instance.handleNumOfPlayersChanged);
});
test('should handle player changed ', () => {
const logSpy = jest.spyOn(console, 'log');
const instance = wrapper.instance() as any;
instance.handleNumOfPlayersChanged();
expect(logSpy).toBeCalledWith('do something');
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/58484558/index.spec.tsx
SomeComponent
✓ should mount component and register socket event (10ms)
✓ should handle player changed (7ms)
console.log node_modules/jest-mock/build/index.js:860
do something
-----------|----------|----------|----------|----------|-------------------|
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: 3.62s, estimated 8s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58484558
I have the following code to test in React
render() {
if (this.state.isDone) {
return(...)
} else {
return(...)
}
}
In the code above, I need to test both conditions. However, when running the below test, one branch is getting tested.
it('renderTest', () => {
const wrapper = shallow(<CheckState />);
expect(wrapper.exists()).toBe(true);
});
In the above code, only the else part gets covered in the test. The parameter in this is assigned during the process of the component. Is it possible for me to test the same by passing a parameter?
You can use setState method of enzyme to change your component state. Below solution only for testing the render method independently without simulate an event.
index.tsx:
import React from 'react';
interface ICheckStateState {
isDone: boolean;
}
export class CheckState extends React.Component<{}, ICheckStateState> {
constructor(props) {
super(props);
this.state = {
isDone: false
};
}
public render() {
if (this.state.isDone) {
return <div>Done</div>;
} else {
return <div>Not Done</div>;
}
}
}
index.spec.tsx:
import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import { CheckState } from './';
describe('CheckState', () => {
describe('#render', () => {
let wrapper: ShallowWrapper;
beforeEach(() => {
wrapper = shallow(<CheckState></CheckState>);
});
it('should render correctly', () => {
expect(wrapper.exists()).toBe(true);
expect(wrapper.text()).toBe('Not Done');
wrapper.setState({ isDone: true });
expect(wrapper.text()).toBe('Done');
});
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/58059957/index.spec.tsx
CheckState
#render
✓ should render correctly (8ms)
-----------|----------|----------|----------|----------|-------------------|
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: 2.819s, estimated 6s
Yes we can do that if we modify the state inside the component to accommodate a specific value from props and if nothing is passed from prop then give a default value, something like this -:
class CheckState extends Component {
constructor(props){
this.state = {
isDone: props.isDone || false
};
}
.......
Also test case needs to be something like this -:
it('renderTest', () => {
const wrapper = shallow(<CheckState />);
expect(wrapper.exists()).toBe(true);
const wrapper = shallow(<CheckState isDone={true}/>);
expect(wrapper.exists()).toBe(true);
});
Enzyme docs contains how to test a node having ref with wrapper.ref('nameOfRef'), but this only works for refs having just a string value like, if I have a node in React:
<span ref="secondRef" amount={4}>Second</span>
Then its test would be written like:
expect(wrapper.ref('secondRef').prop('amount')).to.equal(4);
But if I have a ref with a callback, then how to test it? Enzyme docs [1] does not says anything about this. For example, if I have a node with a ref like this:
<SomeCustomReactElement ref={_form => form = _form} />
Thanks for guidance.
[1]: http://airbnb.io/enzyme/docs/api/ReactWrapper/ref.html
You can call the ref callback manually using wrapper.getElement()['ref'](mockRef).
E.g.
index.tsx:
import React, { Component } from 'react';
export class SomeCustomReactElement extends Component {
doSomething() {
console.log('do somthing');
}
render() {
return <span>some custom react element</span>;
}
}
export default class MyComponent extends Component {
handleRef = (ref: SomeCustomReactElement) => {
console.log('handle ref');
ref.doSomething();
};
render() {
return (
<div>
<SomeCustomReactElement ref={this.handleRef} />
</div>
);
}
}
index.test.tsx:
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent, { SomeCustomReactElement } from './';
describe('48349435', () => {
it('should handle ref', () => {
const wrapper = shallow(<MyComponent />);
const mRef = {
doSomething: jest.fn(),
};
wrapper.find(SomeCustomReactElement).getElement()['ref'](mRef);
expect(mRef.doSomething).toBeCalledTimes(1);
});
});
unit test result:
PASS examples/48349435/index.test.tsx (7.984 s)
48349435
✓ should handle ref (44 ms)
console.log
handle ref
at Object.MyComponent.handleRef [as ref] (examples/48349435/index.tsx:14:13)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 77.78 | 100 | 60 | 77.78 |
index.tsx | 77.78 | 100 | 60 | 77.78 | 5-8
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.273 s