Jest or Mocha: Dynamically create tests based on async initialization

拜拜、爱过 提交于 2020-01-14 19:00:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!