简体   繁体   中英

Testing a REST API with authenticated endpoints

I'm in the process of setting up tests for a NodeJS API (on hapi.js), and I'm not sure what the typical conventions are for testing an authenticated API.

At the moment the route-handlers , authentication and authorization are all in separate modules so I was thinking of testing each module individually rather than calling HTTP endpoints in the tests (which would end up touching all authentication/authorization/handler logic).

However, from what I've seen from some testing guides , there seem to be different opinions on how/what to test. Opinions seem to be:

  1. Call the API endpoint, but only assert on the return status
  2. Call the API endpoint, assert on the return status and the data

If I do call the API endpoint, wouldn't that mean I would need a valid auth token in every use case - or disable auth for testing?

It depends on how many of the endpoints require the same auth. If they all have the same auth and code path, then you can have a few auth tests. They might test:

  1. Auth present
  2. Auth missing
  3. Auth invalid

You can write these 3 tests using the same endpoint. There is no real reason to test other endpoints if they share the same auth code path. In fact, the auth code should be separate from the functionality of each endpoint.

Besides the auth tests, you would have a few tests for each endpoint with a valid auth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM