I have a component Student component as follows
import axios from 'axios';
import React from 'react';
import { useEffect, useState } from 'react';
function Student(props) {
const [studentRecord, setStudentRecord] = useState(props.stRecord);
const [studentSubjects, setStudentSubjects] = useState(null);
function getStudentSubjects() {
let apicalladdress = '/studentapi/GetStudentSubjects/' + studentRecord.studentNumber;
axios.get(apicalladdress).then((result) => {
setStudentSubjects(result.data);
});
}
useEffect(() => {
getStudentSubjects();
}, [studentRecord]);
return (
<div>
<div>{studentRecord.studentNumber}</div>
<div>{setStudentSubjects[0].subjectName}</div>
</div>
);
}
I have a test created as below
import {StudentSubjectsData} from "../globalDataProvider";
import AxiosMock from "axios"
it("make sure student renders",async ()=>{
const mockStudentSubjects=await Promise.resolve({data: StudentSubjectsData()});
AxiosMock.get.mockResolvedValue(mockStudentSubjects);
render (<Student stRecord={StudentRecord}/>);
}
But I am getting following errors
Error 1. An update to Student component inside a test was not wrapped in act(...)
for line :setStudentSubjects(result.data);
Error 2. For following print line, I am getting error TypeError: Cannot read properties of undefined (reading subjectName)
<div>{setStudentSubjects[0].subjectName}</div>
Any suggestions please...
I didn't see how you mock the axios.get() method, I will use jest.spyOn() to mock it.
For the second error, the studentSubjects state is null for the first render. It's better to give an empty array instead of null as its initial value. Besides, you can use optional chain to access the value.
Student.tsx:
import axios from 'axios';
import React from 'react';
import { useEffect, useState } from 'react';
export function Student(props) {
const [studentRecord, setStudentRecord] = useState(props.stRecord);
const [studentSubjects, setStudentSubjects] = useState<{ subjectName: string }[]>([]);
function getStudentSubjects() {
let apicalladdress = '/studentapi/GetStudentSubjects/' + studentRecord.studentNumber;
axios.get(apicalladdress).then((result) => {
setStudentSubjects(result.data);
});
}
useEffect(() => {
getStudentSubjects();
}, [studentRecord]);
return (
<div>
<div>{studentRecord.studentNumber}</div>
<div>{studentSubjects[0]?.subjectName}</div>
</div>
);
}
Student.test.tsx:
import { render, screen } from '#testing-library/react';
import '#testing-library/jest-dom';
import axios from 'axios';
import React from 'react';
import { Student } from './Student';
describe('75502126', () => {
test('should pass', async () => {
const axioGetSpy = jest.spyOn(axios, 'get').mockResolvedValue({ data: [{ subjectName: 'a' }] });
render(<Student stRecord={{ studentNumber: 1 }} />);
expect(await screen.findByText('a')).toBeInTheDocument();
axioGetSpy.mockRestore();
});
});
Test result:
PASS stackoverflow/75502126/Student.test.tsx (8.98 s)
75502126
✓ should pass (34 ms)
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
Student.tsx | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.508 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
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
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
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