简体   繁体   中英

Unit test AWS Lambda with jest and lambda-tester

There are many posts online about how to test AWS lambdas, and how to mock certain dependencies etc. Maybe I am over simplifying, but I don't need any of that. For a while, I have been using mocha/chai and lambda-tester . This worked just fine for running tests with simple npm test .

My problem now is, as I am being ushered towards using Jest instead of mocha/chai, I have since updated all of my tests to match Jest syntax(fairly similar as most are). Now however, my tests sometimes pass and sometimes fail. While this makes me think my tests are not handling async correctly, I do not see how I can make use of the Jest docs and use done in my code, as I believe lambda-tester returns the result I am expecting.

To keep things simple, one of my Lambdas simply returns an image url. My test should verify that has a statusCode:200 and that headers has a content-type property.

Here is my test as it was in mocha/chai format, when it consistently passed (verified not false positives):

describe('Lambda to return imageURl:  ', () => {

  it('should return a status code 200 and have the correct header', () => {
    return LambdaTester( lambda.handler )
      .event( testEvent )
      .expectSucceed( ( result ) => {
        expect( result.statusCode ).to.equal(200);
        expect( result.headers ).to.have.property( 'Location' );
      });
  });
})

Fairly straight forward. Now, here is my updated test in Jest, which is inconsistent:

test('should return a status code 200 and have the correct header', () => {
  return LambdaTester( lambda.handler )
    .event( testEvent )
    .expectSucceed( ( result ) => {
      expect( result.statusCode ).toBe(200);
      expect( result.headers ).toHaveProperty( 'Content-Type' );
    });
});

It is possible that I have missed something in my conversion to Jest, but I cannot see what. Hopefully someone can spot my mistake and help me move forward.

There seems to be nothing wrong with your code.

One of the biggest difference between mocha and jest is that jest runs tests concurrently and therefore it can detect issues like race conditions and mutations outside your handler on your Lambda that mocha may miss.

Here's I would troubleshoot it:

  • Try to run that single test multiple times (that single file and that single test using test.only ).
  • Try running the entire suite serially using jest --runInBand .

If we get consistent failures with those, then you probably have race condition issues and/or maybe a bug in your code where you store state outside of your handler and it is being shared by different invocations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM