I just realized all of my test code has a race condition.
My style pattern follows something like this:
const myFunc = (callback) => {
return somePromise().then((result) => {
return someOtherPromise();
}).then((result) => {
db.end(() => {
callback();
});
}).catch((err) => {
db.end(() => {
callback(err);
});
});
};
I'm testing with Jest. Test code looks something like this.
it('should work', (done) => {
// mock stuff
let callback = () => {
expect(...);
done();
};
myFunc(callback);
});
I have dozens of functions and tests following this pattern. The last test I wrote was giving me a Jest matcher error in my callback. After much confusion, I realized that the first callback execution is throwing the Jest failure, and the callback with the err parameter is being executed and failing before done() is called by the first callback execution.
I'm realizing this pattern might be absolutely terrible. I've managed to beat the race condition by having certain expect() calls in certain order, but that's no way to do this.
How can I remove the potential for the race condition here?
I'm open to completely changing the style I do this. I know my Javascript isn't particularly amazing, and the system is still pretty early in its development.
Aucun commentaire:
Enregistrer un commentaire