How to avoid deep nesting in nodejs tests?
-
26-12-2019 - |
문제
would you mind sharing your best practices in testing nodejs?
What is your experience in order to avoid deep nesting? Could not figure out how to refactor this code to closures when writing test.
describe('ProcessRawData', function(){
describe('event that has been already handled', function(){
beforeEach(function(done){
store.testMode(true);
var filename = __dirname + '/data/test.txt';
fs.readFile(filename, 'utf8', function(err, rawData) {
prd.process(rawData, function(err, data){
var rawMsgSha1 = '123464fbcb34c333f4300a88f019f43e7de757d6';
store.sismember('events:handled', rawMsgSha1, function(err, exists){
if (err) throw err;
assert.ok(exists);
done();
});
});
});
})
해결책
You could consider using an async flow-control library like step
, which would make your code look like this (untested):
describe('ProcessRawData', function(){
describe('event that has been already handled', function(){
beforeEach(function(done){
store.testMode(true);
var filename = __dirname + '/data/test.txt';
Step(
function readFile() {
fs.readFile(filename, 'utf8', this);
},
function processRawData(err, rawData) {
if (err) throw err;
prd.process(rawData, this);
},
function doMoreProcessing(err, data) {
if (err) throw err;
var rawMsgSha1 = '123464fbcb34c333f4300a88f019f43e7de757d6';
store.sismember('events:handled', rawMsgSha1, this);
},
function checkIfExists(err, exists) {
if (err) throw err;
assert.ok(exists);
done();
}
);
});
});
})
제휴하지 않습니다 StackOverflow