Rather than use a string:
assertExpectation("expect(1).toBe(3)");
why not pass a callback, shadowing the global expect
with the env
's:
assertExpectation(function (expect) {
expect(1).toBe(3);
};
This means you can have IDE support on the JS code, rather than at runtime when the eval
fails, and allows you to have multiple soft expectations (and other code) in one callback. You could implement this like:
function assertExpectation(callback) {
const env = new jasmine.Env();
const spec = env.it("", async function () {
await callback(env.expect);
});
return new Promise(function (resolve) {
spec.resultCallback = function (result) {
const messages = result.failedExpectations.map(function (e) {
return e.message;
});
resolve(messages);
}
env.execute();
});
}
Note:
- The
env.describe
was redundant for a single spec;
spec.result
seemed to be populated asynchronously in my testing (using Jasmine 3.5.0), so I've added handling for async code throughout;
- It now handles multiple messages, rather than just the first; and
- Your code is a good example of how not to use comments, they're either redundant repetition of what the code itself does (e.g.
create a variable spec
) or out of date with the actual implementation (...along with the stack
).
Given the following in a discovered test file with the above implementation:
it("works how I want", async () => {
const messages = await assertExpectation(function (expect) {
expect(1).toBe(3);
});
console.log(messages);
expect(1).toBe(1);
});
I get the output
$ npm t
> [email protected] test path/to/soft-expect
> jasmine
Randomized with seed 82972
Started
[ 'Expected 1 to be 3.' ]
.
1 spec, 0 failures
Finished in 0.011 seconds
Randomized with seed 82972 (jasmine --random=true --seed=82972)
if (1 !== 3) { console.log("Maths works") }
). Again, please provide the context behind this request; do a five whys and give the last one rather than the first.