|
| 1 | +// 📌 JavaScript Intermediate - Unit Testing |
| 2 | + |
| 3 | +// Welcome to the tenth section of the JavaScript Advanced tutorial! |
| 4 | +// Here, you'll learn the basics of Unit Testing in JavaScript using Jest. |
| 5 | + |
| 6 | +// What is Unit Testing? |
| 7 | +// Unit testing is a software testing method where individual components (functions, modules) are tested independently to ensure they work correctly. |
| 8 | + |
| 9 | +// Setting Up Jest (if using Node.js) |
| 10 | +// 1. Install Jest: npm install --save-dev jest |
| 11 | +// 2. Add a test script in package.json: "test": "jest" |
| 12 | +// 3. Create a test file, e.g., math.test.js |
| 13 | + |
| 14 | +// Writing a Simple Unit Test with Jest |
| 15 | +// File: math.js |
| 16 | +function add(a, b) { |
| 17 | + return a + b; |
| 18 | +} |
| 19 | +module.exports = add; |
| 20 | + |
| 21 | +// File: math.test.js |
| 22 | +const add = require("./math"); |
| 23 | + |
| 24 | +test("adds 2 + 3 to equal 5", () => { |
| 25 | + expect(add(2, 3)).toBe(5); |
| 26 | +}); |
| 27 | + |
| 28 | +// Run tests with: npm test |
| 29 | + |
| 30 | +// Testing Asynchronous Code |
| 31 | +async function fetchData() { |
| 32 | + return "Hello, World!"; |
| 33 | +} |
| 34 | + |
| 35 | +// File: async.test.js |
| 36 | +const fetchData = require("./async"); |
| 37 | + |
| 38 | +test("fetches correct data", async () => { |
| 39 | + const data = await fetchData(); |
| 40 | + expect(data).toBe("Hello, World!"); |
| 41 | +}); |
| 42 | + |
| 43 | +// Mocking Functions in Jest |
| 44 | +const fetchUser = jest.fn(() => Promise.resolve({ name: "Alice" })); |
| 45 | + |
| 46 | +test("mocks a function call", async () => { |
| 47 | + const user = await fetchUser(); |
| 48 | + expect(user.name).toBe("Alice"); |
| 49 | + expect(fetchUser).toHaveBeenCalled(); |
| 50 | +}); |
| 51 | + |
| 52 | +// 💡 Practice writing unit tests for your functions to ensure your code is reliable and maintainable! |
0 commit comments