Unit test React functional component's function - reactjs

is there anyway we can unit test a function in a react Functional component. Since wrapper.instance() will return null for functional components what's the best way to include this function in test to get maximum coverage.
const SimpleFC: React.FC = () => {
const callbackFunction = () => {
// Do Stuffs
}
return (
<ChildComponent callback={callbackFunction} />
)
}
export { SimpleFC };
In this code segment how can we invoke the callbackFunction ?
Thanks in advance

Through you are using wrapper.instance() API, I arbitrarily think that you are using the enzyme library. You can use .invoke(invokePropName)(...args) => Any method to invoke a function prop on ChildComponent directly.
E.g.
SimpleFC.tsx:
import React from 'react';
import ChildComponent from './ChildComponent';
const SimpleFC: React.FC = () => {
const callbackFunction = () => {
// Do Stuffs
console.log('Do Stuffs');
};
return <ChildComponent callback={callbackFunction} />;
};
export { SimpleFC };
ChildComponent.tsx:
import React from 'react';
export default function ChildComponent({ callback }) {
return <div onClick={callback}>child component</div>;
}
SimpleFC.test.tsx:
import { shallow } from 'enzyme';
import React from 'react';
import { SimpleFC } from './SimpleFC';
describe('67774847', () => {
it('should pass', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = shallow(<SimpleFC />);
wrapper.invoke('callback')();
expect(logSpy).toBeCalledWith('Do Stuffs');
logSpy.mockRestore();
});
});
test result:
PASS examples/67774847/SimpleFC.test.tsx (8.752 s)
67774847
✓ should pass (48 ms)
console.log
Do Stuffs
at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)
--------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files | 90 | 100 | 66.67 | 90 |
ChildComponent.tsx | 66.67 | 100 | 0 | 66.67 | 4
SimpleFC.tsx | 100 | 100 | 100 | 100 |
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.654 s

Related

Enzyme/Jest: Hooks can only be called inside of the body of a function component

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

Fire (dispatch) custom event with react-testing-library

Is there a way to fire a custom event with react-testing-library? I couldn't find such example in their docs.
useEffect(() => {
document.body.addEventListener('customEvent', onEvent);
}, []);
I want to fire custom event (sth. like fireEvent('customEvent') and test if onEvent was called.
You can use fireEvent to dispatch a CustomEvent on document.body HTML element. I added spy to console.log() method to check if the onEvent event handler is called or not.
E.g.
index.tsx:
import React, { useEffect } from 'react';
export function App() {
useEffect(() => {
document.body.addEventListener('customEvent', onEvent);
}, []);
function onEvent(e) {
console.log(e.detail);
}
return <div>app</div>;
}
index.test.tsx:
import { App } from './';
import { render, fireEvent } from '#testing-library/react';
import React from 'react';
describe('67416971', () => {
it('should pass', () => {
const logSpy = jest.spyOn(console, 'log');
render(<App />);
fireEvent(document.body, new CustomEvent('customEvent', { detail: 'teresa teng' }));
expect(logSpy).toBeCalledWith('teresa teng');
});
});
test result:
PASS examples/67416971/index.test.tsx (8.781 s)
67416971
✓ should pass (35 ms)
console.log
teresa teng
at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)
-----------|---------|----------|---------|---------|-------------------
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: 9.638 s
package versions:
"#testing-library/react": "^11.2.2",
"react": "^16.14.0"

What approach should be used to test a SocketIO Client app using Jest?

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

Creating test cases in Jest for render

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);
});

How to test a React ref with a callback?

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

Resources