node.js - Resetting a Node application to a known state when testing with supertest -
i write black box tests against node applications using supertest. app loads database fixtures , black box tests exercise database strenuously. i'd reset app state between tests (so can run different combinations of tests without having worry particular database state).
the ideal thing able reload app another:
var app = require(../app.js).app;
but happens once when run mocha (as should require
calls). think can wrapping tests in multiple mocha calls batch file, developers used running npm test
, , them keep doing that.
how this?
the require
function cache result , won't re-run module. can delete module cache:
delete require.cache[require.resolve('../app')];
if didn't work, can try resetting whole cache: require.cache = {}
but might introduce bugs, because modules developed in way thinking executed once in whole process runtime.
the best way fix write module minimum global state, means instead of storing app module-level value , requiring everywhere, make function builds app , called once , pass needed. avoid problem because call function once per test(originally written loganfsmyth)for example node http server module example can have make several copies of without conflicting each other. @ anytime can close
server shut down.
as repeating mocha calls, can have in npm test:"test" : "mocha file1 && mocha file2 && mocha file3"
Comments
Post a Comment