dwyl / aws-sdk-mock

:rainbow: AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!
Apache License 2.0
1.11k stars 110 forks source link

Mock doesn't work inside of a class #231

Open TooManyLogs opened 3 years ago

TooManyLogs commented 3 years ago

Hi, having some trouble getting mock to work inside a class.

In the following code the mock is not being called at all when testing class

describe(`Mock test`, () => {

    it(`should mock call out from lambda`, done => {

        AWS.mock('Lambda', 'invoke', (params, callback) => callback(null, {
            Payload: {}
        }));

        executeLambda(lambda, event, (callbackErr, callbackDone) => {
            done();
        });
    });

});

This is an example of the class based approach i'm trying to test

module.exports = class MyIntent {

async handle () {
    await this.invoke('myParam');
}

invoke (paramName = {
}) {

    const params = {
        paramName
    };

    return Client.invoke(params)
        .promise()
        .then(response =>
            JSON.parse(response.Payload)
        );
}

};

The same code without class will run the mock when testing

exports.handle = event => {

async function handle () {
    await invoke('myParam');
}

function invoke (paramName = {
}) {

    const params = {
        paramName
    };

    return Client.invoke(params)
        .promise()
        .then(response =>
            JSON.parse(response.Payload)
        );
}

};
thomaux commented 2 years ago

@TooManyLogs I believe the issue here is that your class is not initialised and hence not picked up as a handler.

Change the export statement to:

class MyIntent {
    async handle () {
        await this.invoke('myParam');
    }

    invoke (paramName = {}) {
        const params = {
            paramName
        };

        return Client.invoke(params)
            .promise()
            .then(response =>
                JSON.parse(response.Payload)
            );
        };
    }
}

module.exports = new MyIntent();