0

I have a Javascript class

class Secret {

    constructor(secretName) {
        this.region = "us-east-1";
        this.secretName = secretName;
        this.secretString = ''; // initialize secret string
        //this.jsonParseSecret();
    }

    getSecret() {
        let client = new AWS.SecretsManager({
            region: this.region
        });

        var params = { SecretId: this.secretName}

        client.getSecretValue(params, function(err, data) {
            if (err)
                console.log(err, err.stack); // an error occurred
            else
                console.log(data);           // successful response
                this.secretString = data;
        });
        return this.secretString;
    }
}

Then I am attempting call the getSecret() method from a test

describe('handler', () => {
  test('Test secret.getSecret', async () => {
    var secret = new secrets.Secret("/here/is/my/secret");
    let secretString = secret.getSecret();
    expect(secretString.includes('password')).toBe(true);

  });
});

The problem is that the callback function in client.getSecretValue is executing after the test call expect(secretString.includes('password')).toBe(true);

How can I get the call back to finish before being passed off to the next line of code?

I have tried using await, callbacks, and promises, but I'm definitely not getting it right.

I have tried putting await on the client.getSecretValue() function with the same results.

navig8tr
  • 1,724
  • 8
  • 31
  • 69
  • 1
    client.getSecretValue is asynchronous function you should wait for that response – Hossein Mohammadi Sep 23 '20 at 17:00
  • I have tried putting await on the client.getSecretValue() function with the same results. In this specific case how wold I wait for the response other than with `await`? – navig8tr Sep 23 '20 at 17:26
  • ``` function getSecret() { //other code return new Promise((resolve) => { client.getSecretValue(params, (err, data) => { if (err) resolve(""); else resolve(data); }); }); } ``` – Hossein Mohammadi Sep 24 '20 at 18:59
  • I couldn't answer this question. But I provided an example to show you how to use promise. – Hossein Mohammadi Sep 24 '20 at 19:01

0 Answers0