简体   繁体   中英

Writing tests for REST api NodeJS MongoDB

I am writing a smal REST API in ExpressJS using Mongoose. I have written unit tests for all of the logic inside the app. The only thing that is left untested now is if the API returns the proper status codes and if the restricted resources are in fact restricted.

What I have tried so far:

I tried to use Request to perform GET/POST/PUT/DELETE on a resource, but I find it very clumsy to throw stuff into the db, keep references to the objects and delete it again later.

Is this the smartest way of approaching this? Is my implementation wrong if I need to test something through actual requests with an actual database?

If this is the prefered way of testing the API, is it necessary to test the internal functionality as a complete solution, or should I just test the status codes and the access.

We usually create a test DB and run the tests with NODE_ENV='test' ... which triggers a connection to the test DB.

That way you can wipe the test DB no problem and you don't have to worry about cleaning up before/after tests.

A useful tool for REST testing is superagent (or supertest, though I prefer agent):

Full disclosure: I'm a contributor to superagent.

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