I have a promise where I'm taking the eventual result from the callback and storing it in a value that's scoped outside of the current block in a before
hook, all in one line, like this.
describe('mongo stuff', () => {
let project;
before(() => {
return mongo.findFirst('projects').then(data => project = data);
});
it('should have the correct company name', () => {
expect(project.projectName).to.equal('Company1');
});
});
Note: Mocha, the test runner I'm using, understands promises. That means, placing a return
statement before a promise in a before
hook, or in an it
test, will halt the execution of the next task in the mocha test runner until the promise has been resolved. In other words, data => project = data
will always completely execute before any tests that evaluate the contents of project
are run.
I use data
as a temp variable just so I can assign it to the higher-scoped project
variable. This lets me use it in some later test like in the example above.
I was told in a code review that using an assignment as an expression isn't as clear as writing it out.
return mongo.findFirst('projects').then(data => {
project = data;
});
Which do you think is better? Do you have any solid justification for avoiding the one-liner?