- vừa được xem lúc

Blog#110: 🌸What is Unit Testing and Why is it Important?🌸

0 0 16

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.


Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

Unit testing is a method of testing individual units or components of software, to ensure that they work as intended. In the context of JavaScript, this typically refers to testing individual functions or modules.

Unit testing is important because it allows developers to catch bugs early in the development process, before they make their way into the final product. This can save a lot of time and effort down the road, as fixing bugs in a unit of code is generally much simpler than fixing bugs that have spread throughout the entire application. Additionally, unit tests serve as a form of documentation for the code, as they provide examples of how the code is intended to be used.

Why Node.js Express are good for Unit Testing

Node.js is a popular runtime environment for building server-side applications, and Express is a popular framework for building web applications on top of Node.js. Both Node.js and Express provide a number of features that make them well-suited for unit testing, including:

  • Asynchronous code execution: Node.js and JavaScript are well-suited for handling asynchronous code, which makes it easier to write tests that don't block the execution of other tests.
  • Modular design: Node.js and Express are both based on a modular design, which makes it easy to test individual components of an application in isolation.
  • A large number of testing frameworks: The JavaScript ecosystem has a large number of testing frameworks, such as Jest, Mocha, and Chai, that are specifically designed to help with unit testing.

Example of Unit Testing with Node.js Express or Javascript

Here are some examples of unit testing, along with code samples, to illustrate how unit testing can be applied in different scenarios.

1. Testing a function that performs a mathematical calculation:

const add = (a, b) => a + b; test("add", () => { expect(add(1, 2)).toBe(3); expect(add(-1, -2)).toBe(-3);
});

2. Testing a function that makes an API call:

const fetchData = async () => { const response = await axios.get("https://example.com/data"); return response.data;
}; test("fetchData", async () => { const data = await fetchData(); expect(data).toBeDefined(); expect(data.length).toBeGreaterThan(0);
});

3. Testing a function that accesses a database:

const getUser = async (id) => { const client = new pg.Client(); await client.connect(); const result = await client.query("SELECT * FROM users WHERE id = $1", [id]); await client.end(); return result.rows[0];
}; test("getUser", async () => { const user = await getUser(1); expect(user).toBeDefined(); expect(user.name).toBe("John Doe");
});

4. Testing a function that processes a zip file:

const processZip = async (file) => { const zip = new AdmZip(file); const zipEntries = zip.getEntries(); const data = []; zipEntries.forEach((zipEntry) => { if (!zipEntry.isDirectory) { data.push(zip.readAsText(zipEntry)); } }); return data;
}; test("processZip", async () => { const file = fs.readFileSync("example.zip"); const data = await processZip(file); expect(data).toBeDefined(); expect(data.length).toBeGreaterThan(0); expect(data[0]).toEqual("Example Data");
});

5. Testing a function that process the data to postgresDB and check if the data is being uploaded correctly.

const processData = async (data) => { const client = new pg.Client(); await client.connect(); await client.query("INSERT INTO mytable (data) VALUES ($1)", [data]); const result = await client.query("SELECT * FROM mytable WHERE data = $1", [data]); await client.end(); return result.rows;
}; test("processData", async () => { const data = "Example Data"; const result = await processData(data); expect(result).toBeDefined(); expect(result.length).toEqual(1); expect(result[0].data).toEqual(data);
});

Conclusion

Unit testing is a vital part of the development process that can save a lot of time and effort by catching bugs early. With JavaScript, it is relatively simple to get started with unit testing, and you can use a variety of frameworks such as Jest, Mocha, and Chai to help you. These examples show how you can test different functionality of your application with Node.js Express or JavaScript.

And Finally

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊


The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229