简体   繁体   中英

How to unit-test a AWS Lambda use lambda-local with mocha?

Background

I am working on a project that is build with Serverless framework with serverless-appsync-plugin . I implemented a single endpoint(AWS Lambda) to handle all the requests generate from Appsync through graphQL. The endpoint will route the request to the corresponding function to perform the operation.

Problem

Now that I have developed around 10+ operations, I want to automate the process of unit-testing. For simplicity, I decided to run that single endpoint as a lambda locally for all the testing (against running appsync-offline).

So, I used lambda-local with mocha . However, I am not able to get a test-case to fail, based on the response I got from the lambda.

it('db should have a user of uId: 123',  async function () {
  lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath,
    callback: function(err, data) {
      if(err) {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
      } else {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here too
      }
    }
  });
  console.log(3)
})

In both of the situation I want it to fail, it is not failing the test cases for either callback('failed', null) or callback(null, 'success') .

So, what is the right way to make the lambda-local to fail a test case?

In your code the test finishes without mocha registering that the assertions in lambdaLocal.execute failed. So it will always pass.

Instead of using the callback parameter you could return a promise, or await the lambdalocal.execute and then do your assertions.

For example (using Promises):

it('db should have a user of uId: 123',  function () {
  return lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath })
 .then(
    (data) => {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here
    },
    (err) => {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
    })
}

Alternatively change signature of the function that is passed to it to take an additional parameter (usually called done ) which will then be used by mocha to pass a function that can be used to signalise that the test finished. See the mocha documentation for more info.

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