Skip to content

Instantly share code, notes, and snippets.

@thomaslombart
Last active August 29, 2020 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaslombart/14b89364d44738e5c233a9b3a7ab6e55 to your computer and use it in GitHub Desktop.
Save thomaslombart/14b89364d44738e5c233a9b3a7ab6e55 to your computer and use it in GitHub Desktop.
An example of Counter in React with two different testing tools
import React from "react";
import { shallow } from "enzyme";
import Counter from "./counter";
describe("<Counter />", () => {
it("properly increments and decrements the counter", () => {
const wrapper = shallow(<Counter />);
expect(wrapper.state("count")).toBe(0);
wrapper.instance().increment();
expect(wrapper.state("count")).toBe(1);
wrapper.instance().decrement();
expect(wrapper.state("count")).toBe(0);
});
});
import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import Counter from "./counter";
describe("<Counter />", () => {
it("properly increments and decrements the counter", () => {
render(<Counter />);
const counter = screen.getByText("0");
const incrementButton = screen.getByText("+");
const decrementButton = screen.getByText("-");
fireEvent.click(incrementButton);
screen.getByText("1");
fireEvent.click(decrementButton);
screen.getByText("0");
});
});
import React from "react"
class Counter extends React.Component {
state = { count: 0 }
increment = () => this.setState(({ count }) => ({ count: count + 1 }))
decrement = () => this.setState(({ count }) => ({ count: count - 1 }))
render() {
return (
<div>
<button onClick={this.decrement}>-</button>
<p>{this.state.count}</p>
<button onClick={this.increment}>+</button>
</div>
)
}
}
export default Counter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment