问题
I'm trying to generate tests dynamically by looping over an array returned from an async call. I just cannot figure out how to do this - either using mocha or using jest. To illustrate using code, the following synchronous example works:
describe("Test using various frameworks", () => {
["mocha", "jest"].forEach(framework => {
it(`Should test using ${framework}`, () => {
expect(true).toBe(true);
});
});
});
However, if that array is fetched asynchronously, I cannot get the testing frameworks to wait until the array is fetched before trying to loop over it.
async function getFrameworks() {
//TODO: get it from some async source here
return ["mocha", "jest"];
}
describe("Test using various frameworks", () => {
var frameworks;
//before() instead of beforeAll() if using mocha
beforeAll(async ()=> {
frameworks = await getFrameworks();
});
frameworks.forEach(framework => {
it(`Should test using ${framework}`, () => {
expect(true).toBe(true);
});
});
});
This fails saying Cannot read property 'forEach' of undefined
. I've tried all sort of combinations of using async/await
and Promise
and passing in a done
callback but to no avail.
The closest I came to this was using Mocha's --delay flag, but that only solves part of the problem. What I really want to do in my actual use case is to run some async intialization in the before()
or beforeAll()
hooks which I then use to dynamically generate tests.
Any pointers on how to do this using either mocha or jest?
回答1:
To answer my own question, I did not find a way to do this using Jest or Mocha, but I could accomplish it using tap - which I used through babel-tap.
import tap from "babel-tap";
async function getFrameworks() {
//TODO: get it from some async source here
return ["mocha", "jest"];
}
getFrameworks().then(frameworks => {
frameworks.forEach(framework => {
tap.test(`Should test using ${framework}`, (tester) => {
tester.ok("It works!");
});
});
});
You can do a lot more though. You can create nested scopes by further calling tester.test()
for example. Also, since tap
does not have the concept of before
, after
etc, (unless you use the Mocha-like DSL ), you can simply use imperative code to simulate the equivalent behavior.
Also, you can freely use async/await
style calls inside tests.
来源:https://stackoverflow.com/questions/44240468/jest-or-mocha-dynamically-create-tests-based-on-async-initialization