Dynamically generate data-driven Mocha tests using the data obtained before method

30 views Asked by At

I'm attempting to dynamically generate test cases based on the data retrieved from an API.

Below is the Mocha test class:

describe('Test suite A', function() {
    var serviceClient: ServiceClient;

    var serviceProviderCode: string;

    let negativeTests: any[];

    before(async function() {

        // Retrieve data from dependency services first.
        const networkServiceClient = await ClientFactory.createNetworkServiceClient();

        serviceProviderCode = (await networkServiceClient.getActiveServiceProviderList())[0].companyCode;

        serviceClient = await ClientFactory.createServiceClient();

        negativeTests = CreateMovementData.negative(serviceProviderCode);
    });
    
    negativeTests
        .forEach(({testCase, payload, expectedStatusCode, expectedError}) => {
            it(testCase, async function() {
                const response = await serviceClient.createMovement(payload);
                
                response.status.should.equal(expectedStatusCode);
                expect(response.data.error).to.deep.equal([expectedError]);
            });
        });
});

Below is the class which is responsible for generating the data:

export class CreateMovementData {

    public static negative(serviceProviderCode: string){
        return [
            {
                testCase: "Should not be able to create with service provider only",
                payload: { serviceProvider: serviceProviderCode },
                expectedStatusCode: 400,
                expectedError: {err: "bad request"}
            },
            {
                testCase: "Should not be able to create with invalid delivery service code",
                payload: { serviceProvider: serviceProviderCode, deliveryServiceCode: 'invalid delivery service code'},
                expectedStatusCode: 400,
                expectedError: {err: "bad request"}
            }
        ]
    }

Problem: The negativeTests remains undefined and it is not generating the tests as expected.

Further debugging shows that the negativeTests.forEach(...) being invoked before the before() function completes.

How can I ensure the execution is in the following order?

  1. before() function completes, hence the negativeTests variable had initialized.
  2. negativeTests.forEach invoked to generate the test cases

Any advise / suggestions would be greatly appreciated.

0

There are 0 answers