React के लिए Jest की Basics
In this page:
describe("group name", () => {
test("description", () => {
expect(actual).toBe(expected);
expect(objectValue).toEqual({ key: "value" });
});
});
test() और expect() से एक Basic Test लिखना
एक Jest test test() (या इसका alias it()) का एक call है एक description string और test logic वाले एक function के साथ। अंदर, expect(value) एक assertion शुरू करता है, .toBe() जैसे एक matcher के साथ chained actual result को आपकी उम्मीद के against check करने के लिए।
उदाहरण: Writing a Basic Test with test() and expect()
// Run in your local React project (npm install required)
function add(a, b) { return a + b; }
test('adds two numbers correctly', () => {
expect(add(2, 3)).toBe(5);
});
toBe vs. toEqual
toBe strict equality (===) check करता है, जो primitives के लिए काम करता है लेकिन objects/arrays के लिए fail होता है identical contents के साथ भी, क्योंकि दो separately-created objects कभी === equal नहीं होते। toEqual इसके बजाय एक deep comparison perform करता है, check करते हुए कि actual VALUES match करती हैं, object identity चाहे कुछ भी हो।
उदाहरण: toBe vs. toEqual
// Run in your local React project (npm install required)
test('primitive comparison uses toBe', () => {
expect(2 + 2).toBe(4);
});
test('object comparison uses toEqual', () => {
expect({ name: 'Asha' }).toEqual({ name: 'Asha' }); // passes
// expect({ name: 'Asha' }).toBe({ name: 'Asha' }); // would fail!
});
describe() से Tests को Group करना
describe() related test() calls को एक shared label के under group करता है, एक test file का output organized और scan करना आसान बनाते हुए, especially tests की संख्या बढ़ने के साथ। describe blocks further organization के लिए nested भी हो सकते हैं।
उदाहरण: Grouping Tests with describe()
// Run in your local React project (npm install required)
describe('add function', () => {
test('adds positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('adds negative numbers', () => {
expect(add(-1, -1)).toBe(-2);
});
});
- toBe (strict equality, ===) को toEqual (objects/arrays के लिए deep equality) के साथ confuse करना।
- यह भूल जाना कि test files को automatically pick up होने के लिए Jest के expected naming pattern (जैसे *.test.js) से match करना चाहिए।
- Related tests को group करने के लिए describe() blocks उपयोग न करना, large test files को navigate करना मुश्किल बनाते हुए।
- Jest एक JavaScript test runner है, commonly component tests के लिए React Testing Library के साथ paired।
- test() (या it()) एक individual test case define करता है; describe() related tests को group करता है।
- expect(value).matcher() assertions बनाता है, जैसे toBe, toEqual, या toBeInTheDocument (Testing Library के extensions से)।
- Jest common naming patterns से match करने वाली test files auto-discover करता है, जैसे Component.test.js।
npm install jest चाहिए (या Create React App/Vite templates के साथ pre-configured आता है) — Node में run होता है, इस browser sandbox में नहीं।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: