การทดสอบการผสานรวมเราเตอร์ tRPC
ตั้งค่าการทดสอบการผสานรวมเพื่อตรวจสอบการทำงานร่วมกันอย่างถูกต้องระหว่างกระบวนงาน tRPC และการพึ่งพาต่าง ๆ
การทดสอบการผสานรวมเราเตอร์ tRPC เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน tRPC End-to-End Type Safe APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What are Integration Tests?
Welcome to integration testing for tRPC! While unit tests check individual functions, integration tests verify how different parts of your tRPC application work together.
This often involves testing the interaction between tRPC procedures and external dependencies, like a database or another service.
Unit vs. Integration Tests
Let's clarify the difference:
- Unit Tests: Focus on isolating a single tRPC procedure. They mock all external dependencies to test the procedure's logic alone.
- Integration Tests: Test the flow between multiple procedures or between a procedure and a real (or mocked) external dependency, like ensuring a mutation correctly updates a database.
Setting Up for Integration Tests
For integration tests, you need a controlled environment. This often means:
- Using an in-memory database or a dedicated test database instance.
- Mocking only necessary external services, not core dependencies like your database.
- Setting up a tRPC test caller to invoke procedures directly, bypassing HTTP requests.
Creating a tRPC Test Caller
To call your tRPC procedures directly within tests, you create a test caller. This object lets you interact with your router without a full HTTP server, making tests faster and easier to set up.
Try running this example to see a basic caller in action:
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.context<any>().create();
const publicProcedure = t.procedure;
const appRouter = t.router({
greeting: publicProcedure
.input(z.object({ name: z.string() }).optional())
.query(({ input }) => {
return `Hello, ${input?.name || 'world'}!`;
}),
addNumber: publicProcedure
.input(z.object({ num1: z.number(), num2: z.number() }))
.mutation(({ input }) => {
return input.num1 + input.num2;
}),
});
const caller = appRouter.createCaller({});
async function runSimulatedTest() {
console.log("Simulating tRPC integration test...");
const greetingResult = await caller.greeting.query({ name: "Coddy" });
console.log("Greeting result:", greetingResult);
const sumResult = await caller.addNumber.mutation({ num1: 5, num2: 3 });
console.log("Sum result:", sumResult);
}
runSimulatedTest();Testing a Query Procedure
Integration tests for queries verify that data is fetched correctly, often involving a mock database. We'll ensure the query returns the expected data based on the current state.
Observe how the greeting query behaves with and without input:
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.context<any>().create();
const publicProcedure = t.procedure;
const appRouter = t.router({
greeting: publicProcedure
.input(z.object({ name: z.string() }).optional())
.query(({ input }) => {
// In a real test, this might fetch from a DB
return `Hello, ${input?.name || 'world'}!`;
}),
});
const caller = appRouter.createCaller({});
async function testGreetingQuery() {
console.log("--- Testing 'greeting' query ---");
// Test with a name
const resultWithName = await caller.greeting.query({ name: "Alice" });
console.log("Result with name:", resultWithName);
// Test without a name (default behavior)
const resultNoName = await caller.greeting.query();
console.log("Result no name:", resultNoName);
console.log("Query tests complete.");
}
testGreetingQuery();Testing a Mutation Procedure
Mutations change data. An integration test for a mutation should verify that the data changes as expected and that subsequent queries reflect those changes. We'll simulate an in-memory database.
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.context<any>().create();
const publicProcedure = t.procedure;
// Simulate an in-memory database
const _db: { messages: string[] } = { messages: [] };
const appRouter = t.router({
getMessages: publicProcedure
.query(() => _db.messages),
addMessage: publicProcedure
.input(z.object({ text: z.string() }))
.mutation(({ input }) => {
_db.messages.push(input.text);
return input.text;
}),
});
const caller = appRouter.createCaller({});
async function testAddMessageMutation() {
console.log("--- Testing 'addMessage' mutation ---");
// 1. Check initial state
let initialMessages = await caller.getMessages.query();
console.log("Initial messages:", initialMessages);
// 2. Perform mutation
const addedText = await caller.addMessage.mutation({ text: "Hello tRPC!" });
console.log("Added message:", addedText);
// 3. Check state after mutation
let updatedMessages = await caller.getMessages.query();
console.log("Updated messages:", updatedMessages);
// 4. Perform another mutation
await caller.addMessage.mutation({ text: "More data!" });
updatedMessages = await caller.getMessages.query();
console.log("Further updated messages:", updatedMessages);
console.log("Mutation tests complete.");
}
testAddMessageMutation();Verifying Merged Routers
In larger tRPC applications, you'll organize your API into multiple routers and then merge them into a root router. Integration tests should confirm that procedures from different merged routers can be accessed and interact correctly.
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.context<any>().create();
const publicProcedure = t.procedure;
// Simulate an in-memory database
const _db: { users: string[]; products: string[] } = { users: [], products: [] };
// User router
const userRouter = t.router({
getUsers: publicProcedure.query(() => _db.users),
addUser: publicProcedure
.input(z.object({ name: z.string() }))
.mutation(({ input }) => {
_db.users.push(input.name);
return input.name;
}),
});
// Product router
const productRouter = t.router({
getProducts: publicProcedure.query(() => _db.products),
addProduct: publicProcedure
.input(z.object({ name: z.string() }))
.mutation(({ input }) => {
_db.products.push(input.name);
return input.name;
}),
});
// Root router merging user and product routers
const appRouter = t.router({
user: userRouter,
product: productRouter,
});
const caller = appRouter.createCaller({});
async function testMergedRouters() {
console.log("--- Testing merged routers ---");
// Add a user
await caller.user.addUser.mutation({ name: "Bob" });
const users = await caller.user.getUsers.query();
console.log("Users after adding Bob:", users);
// Add a product
await caller.product.addProduct.mutation({ name: "Laptop" });
const products = await caller.product.getProducts.query();
console.log("Products after adding Laptop:", products);
console.log("All users:", await caller.user.getUsers.query());
console.log("All products:", await caller.product.getProducts.query());
console.log("Merged router tests complete.");
}
testMergedRouters();Testing with Context Data
Many tRPC procedures rely on the context object, which might contain data like an authenticated user's ID or roles. In integration tests, you'll provide a mock context when creating your caller to simulate different user states.
import { initTRPC, TRPCError } from '@trpc/server';
import { z } from 'zod';
// Define the shape of your context
interface MyContext {
userId?: string;
isAdmin?: boolean;
}
const t = initTRPC.context<MyContext>().create();
const publicProcedure = t.procedure;
const protectedProcedure = publicProcedure.use(
t.middleware(({ ctx, next }) => {
if (!ctx.userId) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' });
}
return next({ ctx: { ...ctx, userId: ctx.userId } });
})
);
const adminProcedure = protectedProcedure.use(
t.middleware(({ ctx, next }) => {
if (!ctx.isAdmin) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Not an admin' });
}
return next({ ctx: { ...ctx, isAdmin: ctx.isAdmin } });
})
);
const appRouter = t.router({
whoAmI: protectedProcedure.query(({ ctx }) => `You are user ${ctx.userId}`),
adminAction: adminProcedure.mutation(() => "Admin action successful!"),
});
async function testWithMockContext() {
console.log("--- Testing with mock context ---");
// 1. Test unauthenticated user
const unauthCaller = appRouter.createCaller({});
try {
await unauthCaller.whoAmI.query();
} catch (error: any) {
console.log("Unauthenticated user error:", error.message);
}
// 2. Test authenticated user
const authCaller = appRouter.createCaller({ userId: "user123" });
const userResult = await authCaller.whoAmI.query();
console.log("Authenticated user result:", userResult);
// 3. Test non-admin user trying admin action
try {
await authCaller.adminAction.mutation();
} catch (error: any) {
console.log("Non-admin user error:", error.message);
}
// 4. Test admin user
const adminCaller = appRouter.createCaller({ userId: "admin456", isAdmin: true });
const adminResult = await adminCaller.adminAction.mutation();
console.log("Admin user result:", adminResult);
console.log("Context tests complete.");
}
testWithMockContext();Cleaning Up Test Data
Integration tests that modify shared state (like a database) can create dependencies between tests if not managed carefully. It's crucial to clean up any created data after each test or test suite.
- Use
beforeEach/afterEachhooks in your test runner. - Reset mock databases or truncate tables to ensure tests are isolated and repeatable.
Integration Test Challenge
Consider a tRPC setup where a userRouter handles user creation and a postRouter handles post creation, with posts requiring a valid userId. You are writing an integration test.
Recap: Integration Testing tRPC
We've explored how to perform integration tests for tRPC routers. You learned to:
- Use a test caller to invoke procedures directly.
- Test both query and mutation procedures, observing state changes.
- Verify interactions across merged routers.
- Provide mock context for authenticated tests.
- Understand the importance of test data cleanup.
Integration tests are vital for ensuring your tRPC API's components work harmoniously and correctly interact with dependencies.
เรียนรู้ tRPC End-to-End Type Safe APIs ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 10
- บทเรียน
- 40
คำถามที่พบบ่อย
บทเรียน “การทดสอบการผสานรวมเราเตอร์ tRPC” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การทดสอบการผสานรวมเราเตอร์ tRPC” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส tRPC End-to-End Type Safe APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การทดสอบการผสานรวมเราเตอร์ tRPC”
ตั้งค่าการทดสอบการผสานรวมเพื่อตรวจสอบการทำงานร่วมกันอย่างถูกต้องระหว่างกระบวนงาน tRPC และการพึ่งพาต่าง ๆ คุณปฏิบัติ tRPC End-to-End Type Safe APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน tRPC End-to-End Type Safe APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน tRPC End-to-End Type Safe APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การทดสอบการผสานรวมเราเตอร์ tRPC” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม
ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การทดสอบหน่วยกระบวนงาน tRPC
- การทดสอบการผสานรวมเราเตอร์ tRPC
- กลยุทธ์การทดสอบตั้งแต่ต้นจนจบ
- การจำลองบริบทและการพึ่งพาในการทดสอบ tRPC