πββοΈ How to automate unit testing with Node.js using only standard library [video version available]
This article describes you how to automate unit tests using only the Node.js standard library assert.
The procedure is as follows:
- Preparing for writing source code
- Writing source code
- Preparing for writing test code
- Writing test code
- Operation check
Execute the following command in the terminal to prepare for coding.
mkdir nodejs-test-unit
cd nodejs-test-unit
touch MyMath.js
Open MyMath.js in an editor and enter the following content.
Execute the following command in the terminal to prepare for coding.
touch MyMathTest.js
Open MyMathTest.js in an editor and enter the following content.
The points are as follows:
- Import the source code to be tested.
- The main function lists the test cases to be executed.
- Run the test cases in sequence using the for loop.
- If no exception occurs, OK is output.
- If an exception occurs, an error object is output in addition to NG.
- In the test case, first define 4 variables; the arguments n1 and n2 to be passed to the test target, the actual result, and the expected result.
- Then call the assert.strictEqual function.
Run the following command in the terminal to verify that addTest succeeds and alwaysFailTest fails.
node MyMathTest.js
The execution result of the above command is as follows:
OK addTest
NG alwaysFailTest
AssertionError [ERR_ASSERTION]: alwaysFail
at alwaysFailTest (/Users/susukida/workspace/tech-blog/articles/nodejs-test-unit/MyMathTest.js:39:10)
at main (/Users/susukida/workspace/tech-blog/articles/nodejs-test-unit/MyMathTest.js:17:15) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: undefined,
operator: 'fail'
}
Mocha is famous for unit testing in Node.js. Mocha uses the it function to explain what test cases are doing in English, but I find it difficult for non-native English speakers like me to do so. If your app is small and you don't need to use Mocha, the method presented in this article will suffice. However, as your app grows in size, it becomes increasingly difficult to maintain, so it's better to use Mocha.
In unit tests, it's annoying if the test target contains external dependencies such as accessing the database. In such a case, it is better to cut out only the functional part (the part where the output is determined according to the input only) and perform the unit test, and leave the rest to the API test and UI test. Ideally, you should write source code that is easy to unit test, but you risk sacrificing readability and maintainability. I think it's important to balance just one thing without overweight.
I develop web applications based on the three basics of unit testing, API testing, and UI testing, but I have never systematically learned testing. If you have any recommended books or websites about testing, we would appreciate your guidance and comments. Other comments are welcome. Thank you for reading!