mercredi 10 janvier 2018

Dynamically generate tests in Jest

guys!

I am looking for a way to generate tests in Jest and run them. I am testing an API, and the test cases are imported from a CSV file, from which the tests are generated.

Currently what I've got is an array of parameters, from which I'd like to generate the tests and run them. This is how I see it working:

// This is my test funtion. As I see it, this should be called to execute a test. It generates a test based on the 3 parameters: // testName: the name of the test, to show in the console // request: The request to send to the API // expected: an expected result. The structure is always the same: res.result should be whatever is in the parameter "expect"

let testFn =  (testName, request, expected) => it(test.testName, (request, expected) => {
    return new Promise((resolve, reject) => {
        http.post(request, (err, res) => {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }
        })
    }).then((res) => {
        expect(res.result).toBe(expected['result']);
        return response;
    })
});

// An example of an element from the array with tests that I get from the CSV would be:

const oneTest = {
    testName: 'the request should return 10',
    request: {
        input: 10
    },
    expected: {
        result: 10
    }
}

// Here we go trough the tests array and run all the tests. This is the part I can't make work.

for (let test in tests) {
    testFn.apply(this, [test.testName, test.request, test.expected])
}

The expected result from this is that I'd have all tests generated from the array, run and results shown in the console.

I hope I explained what my problem is clear enough, but if that's not the case, please don't hesitate to ask (you're helping me after all!)

PS: This is my first time using Jest, so I might be assuming many things in a wrong way. If you see some complete stupidity, please note it, I'm happy to learn! :)

Aucun commentaire:

Enregistrer un commentaire