This article describes how to automate API testing by using fetch in Node.js. We install node-fetch npm package to enable fetch in Node.js.
The workflow is as follows:
- Preparing to write source code
- Writing source code
- Preparing to write test code
- Writing test code
- Operation check
Execute the following command in the terminal to prepare for coding.
mkdir nodejs-test-api
cd nodejs-test-api
npm init -y
npm install --save express
npm install --save-dev node-fetch@2
touch api.js
If you want to import node-fetch using require (require('node-fetch')
), it needs to be version 2, so add @2 to the end and install it.
Open api.js in an editor and enter the following content
Execute the following command in the terminal to prepare for coding.
touch api.test.js
Open api.test.js in an editor and enter the following content.
The points are as follows:
- Import node-fetch as fetch.
- Call the fetch function to access the API.
- Use assert.strictEqual to check that the actual value, such as the status code, matches the expected value.
- It is convenient to use assert.deepStrictEqual to check the whole object match.
Execute the following command in the terminal to start the API.
node api.js
Open a new terminal and run the following command to run the API test.
node api.test.js
Confirm that the execution result of the above command matches the following.
{ actual: { ok: true }, expected: { ok: true } }
OK getApiStatusTest
While axios is a well-known library for sending HTTP requests, fetch is the standard API for front-end JavaScript. By installing node-fetch and making fetch available in Node.js, you can reduce the amount of memorization.
Compared to unit tests and UI tests, API tests can handle database access, etc., and test code is easy to write, so it is more useful than the other two. When doing API testing, it is useful to be able to initialize the database when needed.
Some web apps require authentication or authorization to access the API. If you're using OAuth 2.0 and can use Client Credentials Grant, it's not too much of a hassle as it only adds to the effort of getting an access token such as JWT from an authorization endpoint such as Auth0. On the other hand, if you use cookies for authentication, it's a bit annoying. I manually log in with a web browser, then use developer tools to find and copy the cookie and pass it using environment variables etc. when running the test code. This method is tedious and not secure, so if anyone knows a good way, I would appreciate your guidance and comments. Other comments are welcome. Thank you for reading!