使用 Jest 进行单元测试
学习使用 Jest 测试框架,为单个函数和模块编写隔离的单元测试。
使用 Jest 进行单元测试 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is Unit Testing?
Welcome to unit testing! This is a fundamental practice in software development where individual components or functions of your application are tested in isolation.
Think of it like checking each gear in a clock separately to ensure it works perfectly before assembling the whole mechanism. This helps catch bugs early!
Meet Jest: Your Testing Buddy
For Node.js, Jest is one of the most popular and developer-friendly testing frameworks. It's developed by Facebook and offers a complete, integrated solution for JavaScript testing.
- Zero Config: Often works out of the box.
- Fast: Designed for performance.
- Rich API: Powerful assertion library (matchers) included.
- Snapshot Testing: Great for UI components.
Installing Jest
Getting started with Jest is easy. You'll install it as a development dependency in your Node.js project. Open your terminal in your project's root directory and run:
npm install --save-dev jest
After installation, you can add a script to your package.json file to easily run your tests:
"scripts": { "test": "jest" }
Our First Function to Test
Let's write a simple function that we want to test. This function will add two numbers. We'll put it in a file named sum.js.
You can run this file directly to see the function in action, but later we'll use Jest to test it automatically!
function sum(a, b) {
return a + b;
}
// This allows us to use 'sum' in other files
module.exports = sum;
// Optional: Run this part only if the file is executed directly
if (require.main === module) {
console.log("Running sum(2, 3):");
console.log("Result: ", sum(2, 3)); // Expected: 5
}Structuring Your Test File
Jest looks for test files with specific naming conventions, usually .test.js or .spec.js. Let's create sum.test.js in the same directory.
Inside, we use describe() to group related tests and test() (or it()) for individual test cases. This makes your tests organized and readable.
Making Assertions with Matchers
Inside a test() block, we use expect() combined with a "matcher" to assert that a value meets certain conditions. For example, .toBe() checks for exact equality.
Here's how we'd test our sum function:
const sum = require('./sum');
describe('sum function', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('adds 0 + 0 to equal 0', () => {
expect(sum(0, 0)).toBe(0);
});
test('adds negative numbers correctly', () => {
expect(sum(-1, -2)).toBe(-3);
});
});Running Your Tests
Now that you have your sum.js and sum.test.js files, and Jest installed with the script configured, you can run your tests!
Simply type npm test in your terminal. Jest will find your .test.js files, execute them, and report the results. You'll see green if all tests pass!
Handling Async Tests
Many Node.js applications deal with asynchronous operations (like fetching data, database calls). Jest handles these beautifully!
You can use async/await directly in your test functions. Jest will wait for the promise to resolve before completing the test.
function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Data from API");
}, 50);
});
}
module.exports = fetchData;
// Optional: Run this part only if the file is executed directly
if (require.main === module) {
console.log("Simulating data fetch...");
fetchData().then(data => console.log("Received: ", data));
}Writing Async Tests
To test our fetchData function, we'll mark our test function as async. Jest also provides special matchers like .resolves and .rejects for promises.
Using await within your test makes asynchronous code look synchronous, improving readability.
const fetchData = require('./fetchData');
describe('fetchData function', () => {
test('should return "Data from API"', async () => {
const data = await fetchData();
expect(data).toBe('Data from API');
});
test('should resolve with specific data', () => {
return expect(fetchData()).resolves.toBe('Data from API');
});
});Jest Matcher Check
Which of the following Jest matchers would you use to check if two objects have the same value (deep comparison), not just if they are the same instance?
Unit Testing with Jest: Recap
Great job! You've learned the basics of unit testing with Jest. We covered:
- What unit testing is and its benefits.
- How to install and set up Jest.
- Structuring tests with
describeandtest. - Making assertions using
expectand matchers like.toBe()and.toEqual(). - Handling asynchronous code with
async/await.
Keep practicing and happy testing!
常见问题解答
「使用 Jest 进行单元测试」课时是免费的吗?
是的 — 「使用 Jest 进行单元测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「使用 Jest 进行单元测试」这节课中我会学到什么?
学习使用 Jest 测试框架,为单个函数和模块编写隔离的单元测试。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「使用 Jest 进行单元测试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 Jest 进行单元测试
- 集成测试 API 端点
- 高效调试技巧
- Node.js 中的模拟与测试替身