TypeScript के साथ Jest
In this page:
import { functionName } from "./module";
describe("name", () => {
it("does something", () => {
expect(functionName(input)).toBe(expected);
});
});
एक Simple Jest Test
एक TypeScript project में एक basic Jest test plain JavaScript जैसी ही describe/it/expect API उपयोग करता है, लेकिन ts-jest (या Babel का TypeScript preset) Jest के चलाने से पहले .ts test file को compile करता है, आपके tests में खुद type errors catch करते हुए।
उदाहरण: A Simple Jest Test
// sum.test.ts
function sum(a: number, b: number) { return a + b; }
// test("adds numbers", () => { expect(sum(1, 2)).toBe(3); });
console.log(sum(1, 2));
Typed Functions Test करना
एक typed function test करना Jest के type checker को यह flag करने देता है कि एक test function को गलत argument types से call करता है test असल में चलने से पहले, bugs की एक class catch करते हुए जो plain JavaScript tests नहीं कर सकते।
उदाहरण: Testing Typed Functions
function double(x: number): number { return x * 2; }
// test("doubles a number", () => { expect(double(5)).toBe(10); });
// double("5") would be a compile-time error, caught before the test runs
console.log(double(5));
Async Functions Test करना
Async functions test करने के लिए test body के अंदर call को await करना चाहिए (या promise return करना), और TypeScript resolved type infer करेगा इसलिए expect() assertions असली return shape के against type-checked होते हैं।
उदाहरण: Testing Async Functions
async function fetchValue(): Promise<number> { return 42; }
// test("resolves with 42", async () => { expect(await fetchValue()).toBe(42); });
fetchValue().then(console.log);
Errors Test करना
यह test करना कि एक function throw करता है expect(() => fn()).toThrow() उपयोग करता है, call को एक arrow function में wrap करते हुए ताकि Jest खुद thrown error catch कर सके बजाय test के crash होने के assertion चलने से पहले।
उदाहरण: Testing Errors
function mustBePositive(n: number): number {
if (n < 0) throw new Error("must be positive");
return n;
}
// test("throws on negative", () => { expect(() => mustBePositive(-1)).toThrow(); });
try { mustBePositive(-1); } catch (e) { console.log("threw as expected"); }
Typed Test Data
Typed test data — fixture objects बनाना जो एक interface को satisfy करें — compile time पर एक broken fixture catch करता है अगर जिस shape के against यह test कर रहा है वह कभी बदले, runtime पर confusingly fail होने के बजाय।
उदाहरण: Typed Test Data
interface User { id: number; name: string; }
const fixture: User = { id: 1, name: "Test User" };
// test("fixture matches User shape", () => { expect(fixture.name).toBe("Test User"); });
console.log(fixture);
@types/jestभूल जाना, इसलिएdescribe,it, औरexpectunknown names हैं।- Objects को
toBeसे compare करना, जो identity check करता है, जब equal contents के लिएtoEqualचाहिए। - एक function जो throw करे उसे
expect(() => fn())के बजाय सीधेexpect(fn())के अंदर call करना, इसलिए error assertion से escape हो जाती है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: