Creating test cases in Jest for render - reactjs

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

Related

How do I test the parameters of a context function called within a component function?

I've seen a number of examples on how to mock context and how to mock a specific component function call but I haven't found one that does both at the same time. Most cases for properly mocking context suggest using mount(), but then that doesn't give me access to the instance returned from shallow(<MyComponent>).instance() which I would then use to make the function call. This is an example of the situation I'm trying to test:
class MyComponent extends Component {
static contextType = MyContext
constructor(props) {
super(props);
this.myFunction = this.myFunction.bind(this);
}
myFunction() {
this.context.otherFunction('shouldBecorrectValue');
}
}
Ideally, I'd like to be able to do this without changing the code under test.
There is .instance() => ReactComponent method for the wrapper returned by mount. Only works for class component.
Returns the single-node wrapper's node's underlying class instance.
index.tsx:
import React, { Component } from 'react';
const MyContext = React.createContext({
otherFunction: (value) => {
console.log(value);
},
});
export class MyComponent extends Component {
static contextType = MyContext;
myFunction() {
this.context.otherFunction('shouldBecorrectValue');
}
render() {
return <div>my component</div>;
}
}
index.test.tsx:
import { mount } from 'enzyme';
import React from 'react';
import { MyComponent } from './';
describe('69127076', () => {
test('should pass', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = mount(<MyComponent />);
wrapper.instance()['myFunction']();
expect(logSpy).toBeCalledWith('shouldBecorrectValue');
logSpy.mockRestore();
});
});
test result:
PASS examples/69127076/index.test.tsx (10.228 s)
69127076
✓ should pass (47 ms)
console.log
shouldBecorrectValue
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: 10.804 s
package versions:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0",
"react-dom": "^16.14.0",

Unit test React functional component's function

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

How to fix 'Expected mock function to have been called, but it was not called' in Jest

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

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

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