Skip to content

Instantly share code, notes, and snippets.

@ivanbtrujillo
Forked from gomezcabo/sum1.test.tsx
Created July 4, 2019 10:19
Show Gist options
  • Save ivanbtrujillo/da26337cd63446e58d745ca4dd310ebd to your computer and use it in GitHub Desktop.
Save ivanbtrujillo/da26337cd63446e58d745ca4dd310ebd to your computer and use it in GitHub Desktop.
import Sum from './Sum';
describe('Sum', () => {
it('should render', () => (
));
it('should have two inputs to add the numbers', () => (
));
it('should have a button to fire the sum action', () => (
));
it('should have text to show the result', () => (
));
it('should sum value1 and value2 and show the result', () => (
));
})
import React from "react";
const Sum = () => <div />;
export default Sum;
import React from "react";
import { render, cleanup, fireEvent } from "@testing-library/react";
import Sum from "./Sum";
describe("Sum", () => {
afterEach(cleanup)
it("should render", () => {
const SumComponent = render(<Sum />);
expect(SumComponent).toBeTruthy();
});
});
import React from "react";
const Sum = () => (
<div>
<input data-testid="value1" />
<input data-testid="value2" />
</div>
);
export default Sum;
import React from "react";
import { render, cleanup, fireEvent } from "@testing-library/react";
import Sum from "./Sum";
describe("Sum", () => {
it('should have two inputs to add the numbers', () => {
const { getByTestId } = render(<Sum />);
const firstInput = getByTestId("value1");
const secondInput = getByTestId("value2");
expect(firstInput).toBeTruthy();
expect(secondInput).toBeTruthy();
});
});
import React, { useState } from "react";
const Sum = () => {
const [value1, setValue1] = useState();
const [value2, setValue2] = useState();
const [result, setResult] = useState();
const calculateSum = () => setResult(value1 + value2);
return (
<div>
<input
data-testid="value1"
value={value1}
onChange={e => setValue1(e.target.value)}
/>
<input
data-testid="value2"
value={value2}
onChange={e => setValue2(e.target.value)}
/>
<button data-testid="sum-button" onClick={calculateSum} />
<p data-testid="result-txt">{result}</p>
</div>
);
};
export default Sum;
import React from "react";
import { render, cleanup, fireEvent } from "@testing-library/react";
import Sum from "./Sum";
import "jest-dom/extend-expect";
describe("Sum", () => {
it('should sum value1 and value2 and show the result', () => {
const { getByTestId } = render(<Sum />);
const firstInput= getByTestId("value1");
fireEvent.change(firstInput, { target: { value: 1 } } );
const secondInput= getByTestId("value2");
fireEvent.change(secondInput, { target: { value: 1 } } );
const sumBtn = getByTestId("sum-button");
fireEvent.click(sumBtn);
const result = getByTestId("result-txt");
expect(result).toHaveTextContent(2);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment