Robert Moskal
Robert Moskal

Reputation: 22553

Resetting a Node application to a known state when testing with supertest

I often write black box tests against my node applications using supertest. The app loads up database fixtures and the black box tests exercise the database strenuously. I'd like to reset the app state between certain tests (so I can run different combinations of tests without having to worry about a particular database state).

The ideal thing would be to be able to reload the app with another:

var app = require(../app.js).app; 

But this only happens once when I run mocha (as it should be with require calls). I think I can do it by wrapping my tests in multiple mocha calls from a batch file, but my developers are used to running npm test, and I would like them to keep doing that.

How could I do this?

Upvotes: 1

Views: 1815

Answers (2)

Robert Moskal
Robert Moskal

Reputation: 22553

The correct answer is to be found in the above answer, the best thing to do is to build the app in a function. This question is answered here:

grunt testing api with supertest, express and mocha

One can also break the mocha command line up as it says towards the end, but isn't as desirable since it messes up the reporting.

Upvotes: 1

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30430

The require function will basically cache the result and it won't re-run the module. But you can delete the module from the cache:

delete require.cache[require.resolve('../app')];

If that didn't work, you can try resetting the whole cache: require.cache = {}

But that might introduce bugs, because usually modules are developed in a way thinking that they will be only executed once in the whole process runtime.

The best way to fix is to write module with the minimum global state, which means instead of storing the app as a module-level value and then requiring it everywhere, I would make a function that builds the app and is called once and then pass it where it is needed. Then you avoid this problem because you just call that function once per test(originally written by loganfsmyth)For example node http server module is a good example where you can have make several copies of it without conflicting each other. At anytime you can close a server to shut it down.

As for repeating mocha calls, you can have it in your npm test:"test" : "mocha file1 && mocha file2 && mocha file3"

Upvotes: 3

Related Questions