Test এর উদ্দেশ্য coverage সংখ্যা না, ভয় ছাড়া কোড বদলানোর আত্মবিশ্বাস। Implementation নয়, behavior test করো: user কী দেখে, API কী return করে।
Test এর ধরন
| ধরন | কী test করে | Speed | Tool |
|---|---|---|---|
| Unit | একটা function/class, dependency mock | খুব দ্রুত | Vitest, Jest, pytest |
| Integration | কয়েকটা অংশ একসাথে (API + আসল DB) | মাঝারি | Supertest, httpx, Testcontainers |
| Component | UI component user এর মতো | দ্রুত | React Testing Library |
| E2E | পুরো flow আসল browser এ | ধীর | Playwright, Cypress |
| Contract | Service এর API contract মিলছে কিনা | দ্রুত | Pact |
| Load | চাপে কেমন চলে | — | k6, Artillery |
Testing trophy/pyramid: অনেক unit, সবচেয়ে বেশি মূল্য integration test এ, অল্প কিছু critical E2E (login, checkout, payment)।
React Testing Library
test("shows error on wrong password", async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={vi.fn().mockRejectedValue(new Error("Invalid"))} />);
await user.type(screen.getByLabelText(/email/i), "a@b.com");
await user.type(screen.getByLabelText(/password/i), "wrong");
await user.click(screen.getByRole("button", { name: /log in/i }));
expect(await screen.findByRole("alert")).toHaveTextContent("Invalid");
});
- Query priority:
getByRole>getByLabelText>getByText>getByTestId। Role দিয়ে খুঁজলে accessibility ও test হয়ে যায়। - Network mock এর জন্য MSW (Mock Service Worker)।
Backend integration test
it("POST /orders returns 201", async () => {
const res = await request(app)
.post("/v1/orders")
.set("Authorization", `Bearer ${token}`)
.send({ productId: 1, qty: 2 });
expect(res.status).toBe(201);
expect(await db.order.count()).toBe(1);
});
- আসল database দিয়ে test করো (Docker বা Testcontainers); mock DB অনেক bug লুকিয়ে রাখে।
- প্রতিটা test আলাদা: transaction rollback বা table truncate।
- বাইরের service (payment, email) mock করো, নিজের code নয়।
ভালো test এর নিয়ম
- Arrange → Act → Assert গঠন; এক test এ একটা behavior।
- Test এর নাম বলবে কী হওয়া উচিত ("returns 404 when order belongs to another user")।
- Flaky test (কখনো pass, কখনো fail) সাথে সাথে ঠিক করো; সাধারণ কারণ time, random, shared state,
sleep। - Bug fix এর আগে সেই bug ধরে এমন failing test লেখো (regression test)।
- TDD: আগে test (red) → কোড (green) → refactor। সবসময় না হলেও, জটিল logic এ কাজের।
Interview প্রশ্ন
- Unit, integration আর E2E test এর পার্থক্য? কোনটা কতটা লিখবে?
- Mock, stub, spy এর পার্থক্য?
- Database আছে এমন code কীভাবে test করবে?
- Flaky test কেন হয়, কীভাবে ঠিক করবে?
- একটা component এর জন্য test লেখো (live coding)।