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

image.png

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. 😊

NGUYỄN ANH TUẤN

Xin chào, mình là Tuấn, một kỹ sư phần mềm đang làm việc tại Tokyo. Đây là blog cá nhân nơi mình chia sẻ kiến thức và kinh nghiệm trong quá trình phát triển bản thân. Hy vọng blog sẽ là nguồn cảm hứng và động lực cho các bạn. Hãy cùng mình học hỏi và trưởng thành mỗi ngày nhé!

Đăng nhận xét

Mới hơn Cũ hơn