Let's say I have a simple component like this.
I want to write test cases using jest and enzyme. But counter.instance()
always returns null.
Any help will be greatly appreciated.
import React from "react";
import Counter from "../components/Counter";
import {
mount,
shallow
} from "./enzyme";
describe("Counter", () => {
let counter;
beforeEach(() => {
counter = shallow( < Counter / > );
})
it("calls incCounter function when button is clicked", () => {
console.log(counter)
counter.instance().incCounter = jest.fn();
const incButton = counter.find("button");
incButton.simulate("click");
expect(counter.incCounter).toBeCalled();
})
});
From this docs: https://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
NOTE: can only be called on a wrapper instance that is also the root instance. With React 16 and above, instance() returns null for stateless functional components.
Test component behavior, not implmentation details.
E.g.
index.jsx
:
import React, { useState } from 'react';
const Counter = () => {
const [counter, setCounter] = useState(0);
const incCounter = () => {
setCounter(counter + 1);
};
return (
<>
<p>Counter value is: {counter}</p>
<button className="increment" onClick={incCounter}>
Up
</button>
</>
);
};
export default Counter;
index.spec.jsx
:
import React from 'react';
import Counter from './';
import { shallow } from 'enzyme';
describe('Counter', () => {
let counter;
beforeEach(() => {
counter = shallow(<Counter />);
});
it('calls incCounter function when button is clicked', () => {
expect(counter.find('p').text()).toBe('Counter value is: 0');
const incButton = counter.find('button');
incButton.simulate('click');
expect(counter.find('p').text()).toBe('Counter value is: 1');
});
});
Unit test result with 100% coverage:
PASS src/stackoverflow/59475724/index.spec.jsx (10.045s)
Counter
✓ calls incCounter function when button is clicked (17ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.jsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.697s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59475724