xxxxxxxxxx
test('Addition test', () => {
// Arrange
const a = 2;
const b = 3;
// Act
const result = a + b;
// Assert
expect(result).toBe(5);
});
xxxxxxxxxx
npm i jest --save -dev
-> In Package.json change the Script object(watchAll - jest will run auto)
"test" : "jest --watchAll"
-> test file should be named such way that re used by jest can recognize it
like filename.<test> or <spec> or skip it.js
Ex: sum.test.js or sum.spec.js or sum.js
-> require the target for testing file in this test file then enjoy testing.
-> visit jestWebsite-> Docs.
xxxxxxxxxx
const cal = require('../index');
test('adds 1 + 2 to equal 3', () => {
expect(cal.sum(1, 2)).toBe(3);
expect(cal.sum(1, 2)).not.toBe(4);
expect(cal.sum(1, 2)).toBeGreaterThan(2);
expect(cal.sum(1, 2)).toBeLessThan(4);
expect(cal.sum(1, 2)).toBeCloseTo(3);
// Testing datatype
expect(typeof cal.sum(1, 2)).toBe("number");
});
xxxxxxxxxx
import React, { useState } from "react";
const Counter = () => {
const [counter, setCounter] = useState(0);
const incrementCounter = () => {
setCounter((prevCounter) => prevCounter + 1);
};
const decrementCounter = () => {
setCounter((prevCounter) => prevCounter - 1);
};
return (
<>
<button data-testid="increment" onClick={incrementCounter}>
+
</button>
<p data-testid="counter">{counter}</p>
<button disabled data-testid="decrement" onClick={decrementCounter}>
-
</button>
</>
);
};
export default Counter;
xxxxxxxxxx
// myMath.js
const myMath = {
sum: (a, b) => a + b,
subtract: (a, b) => a - b,
};
module.exports = myMath;