# Unit Tests in Serverless

**URL:** <https://discourse.sst.dev/t/unit-tests-in-serverless/173>\
**Category:** Chapter Comments\
**Created:** [May 9, 2018, 11:18pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173 "2018-05-09T23:18:49Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![jayair](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/jayair/32/9_2.png) [@jayair](https://discourse.sst.dev/u/jayair)\
**Post date:** [May 9, 2018, 11:18pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/1 "2018-05-09T23:18:49Z")

</div>

Link to chapter - [https://serverless-stack.com/chapters/unit-tests-in-serverless.html](https://serverless-stack.com/chapters/unit-tests-in-serverless.html)

---

<div class="post-metadata">

**Author:** ![filipesmedeiros](https://avatars.discourse-cdn.com/v4/letter/f/6f9a4e/32.png) [@filipesmedeiros](https://discourse.sst.dev/u/filipesmedeiros)\
**Post date:** [March 27, 2019, 3:51pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/2 "2019-03-27T15:51:04Z")

</div>

Hey! Got the error:

FAIL tests/billing.test.js  
● Test suite failed to run

```
Plugin/Preset files are not allowed to export objects, only functions. In D:\simply\noteit\noteit-api\node_modules\babel-preset-stage-3\lib\index.js

  at createDescriptor (node_modules/@babel/core/lib/config/config-descriptors.js:178:11)
  at items.map (node_modules/@babel/core/lib/config/config-descriptors.js:109:50)
      at Array.map (<anonymous>)
  at createDescriptors (node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
  at createPresetDescriptors (node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
  at presets (node_modules/@babel/core/lib/config/config-descriptors.js:47:19)
  at mergeChainOpts (node_modules/@babel/core/lib/config/config-chain.js:320:26)
  at node_modules/@babel/core/lib/config/config-chain.js:283:7
  at buildRootChain (node_modules/@babel/core/lib/config/config-chain.js:120:22)
  at loadPrivatePartialConfig (node_modules/@babel/core/lib/config/partial.js:85:55)

```

Test Suites: 1 failed, 1 total  
Tests: 0 total  
Snapshots: 0 total  
Time: 1.818s  
Ran all test suites.  
npm ERR! Test failed. See above for more details.

When running npm test. My package.json (different because trying to solve issue):

 ![packagejson](https://canada1.discourse-cdn.com/flex032/uploads/serverless_stack/original/1X/89c0a8878495a6b2dc7843f70efcf271db1539b6.png)

Thanks

EDIT: copied exact package.json you guys have on GitHub, and only changed Jest to isolate. It seems Jest 24.5.0 has some problems with Babel.  
Also, this makes builds fail when using Seed’s auto-deploy (with unit testing enabled)!  
EDIT2: the problem arises from Jest 24.0.1 and up, 23.6.0 is fine. The should be a way to make Jest and Babel work fine together right?

---

<div class="post-metadata">

**Author:** ![filipesmedeiros](https://avatars.discourse-cdn.com/v4/letter/f/6f9a4e/32.png) [@filipesmedeiros](https://discourse.sst.dev/u/filipesmedeiros)\
**Post date:** [March 27, 2019, 7:12pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/3 "2019-03-27T19:12:00Z")

</div>

So I think I figured this out. Turns out I couldn’t find a way to make the plugins work (transform-runtime and source-map-support) but it seems to work fine without them. So with Jest and Babel updated, this is what my package.json (in part) and .babelrc look like:

package.json

“devDependencies”: {  
 “@babel/cli”: “^7.2.3”,  
 “@babel/core”: “^7.4.0”,  
 “@babel/node”: “^7.2.2”,  
 “@babel/plugin-transform-runtime”: “^7.4.0”,  
 “@babel/preset-env”: “^7.4.2”,  
 “aws-sdk”: “^2.224.1”,  
 “babel-jest”: “^24.5.0”,  
 “babel-loader”: “^8.0.5”,  
 “babel-plugin-transform-runtime”: “^6.23.0”,  
 “jest”: “^24.5.0”,  
 “serverless-offline”: “^3.18.0”,  
 “serverless-webpack”: “^5.1.0”,  
 “webpack”: “^4.2.0”,  
 “webpack-node-externals”: “^1.6.0”  
},  
“dependencies”: {  
 “aws-sdk”: “^2.422.0”,  
 “babel-runtime”: “^6.26.0”,  
 “semver”: “^6.0.0”,  
 “serverless”: “^1.39.1”,  
 “source-map-support”: “^0.4.18”,  
 “stripe”: “^6.28.0”,  
 “uuid”: “^3.3.2”  
},  
“jest”: {  
 “testEnvironment”: “node”  
}

.babelrc

{  
 “presets”: [  
 “jest”,  
 [  
 “@babel/preset-env”,  
 {  
 “debug”: false,  
 “modules”: “commonjs”,  
 “targets”: {  
 “node”: “current”  
 },  
 “useBuiltIns”: false  
 }  
 ]  
 ]  
}

And now it passes Jest tests!

---

<div class="post-metadata">

**Author:** ![gfting](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/gfting/32/547_2.png) [@gfting](https://discourse.sst.dev/u/gfting)\
**Post date:** [July 28, 2019, 2:19pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/4 "2019-07-28T14:19:13Z")

</div>

Thank you so much, adding the .babelrc fixed my issue! For others encountering the same problem, you don’t need the extra dependences.

---

<div class="post-metadata">

**Author:** ![prgtrdr](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/prgtrdr/32/556_2.png) [@prgtrdr](https://discourse.sst.dev/u/prgtrdr)\
**Post date:** [August 3, 2019, 4:45pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/5 "2019-08-03T16:45:13Z")

</div>

Thanks so much. Creating the .babelrc fixed the problem for me as well, didn’t have to change anything else. Here it is with proper formatting:

> ```
> {
> "presets": [
> "jest", [
> "@babel/preset-env", {
> "debug": false,
> "modules": "commonjs",
> "targets": {
> "node": "current"
> },
> "useBuiltIns": false
> }
> ]
> ]
> }
> 
> ```

@jayair: You should probably add this to the repo, or at least mention it in the text.

---

<div class="post-metadata">

**Author:** ![jayair](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/jayair/32/9_2.png) [@jayair](https://discourse.sst.dev/u/jayair)\
**Post date:** [August 4, 2019, 12:54am UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/7 "2019-08-04T00:54:54Z")

</div>

Are you using the `serverless-bundle` plugin? Cos we recently updated things to get rid of all the Webpack and Babel configs.

---

<div class="post-metadata">

**Author:** ![jerrynim](https://avatars.discourse-cdn.com/v4/letter/j/94ad74/32.png) [@jerrynim](https://discourse.sst.dev/u/jerrynim)\
**Post date:** [August 4, 2019, 7:20am UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/8 "2019-08-04T07:20:54Z")

</div>

let’s use es2015

```auto
module.exports = function calculateCost(storage) {
  const rate = storage <= 10 ? 4 : storage <= 100 ? 2 : 1;

  return rate * storage * 100;
};

```

```auto
const calculateCost = require("../libs/billing-lib");

```

---

<div class="post-metadata">

**Author:** ![shadow](https://avatars.discourse-cdn.com/v4/letter/s/5fc32e/32.png) [@shadow](https://discourse.sst.dev/u/shadow)\
**Post date:** [September 24, 2019, 9:59am UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/9 "2019-09-24T09:59:23Z")

</div>

```
D:\Shadow\Desktop\serverless-stack-2-api>npm test

> serverless-nodejs-starter@1.1.0 test D:\Shadow\Desktop\serverless-stack-2-api
> jest

 FAIL tests/billing.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    D:\Shadow\Desktop\serverless-stack-2-api\tests\billing.test.js:1
    ({"Object.<anonymous>":function(module,exports,require, __dirname,__ filename,global,jest){import { calculateCost } from "../libs/billing-lib";
                                                                                                    ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/node_modules/@jest/transform/build/ScriptTransformer.js:537:17)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 4.374s
Ran all test suites.
npm ERR! Test failed. See above for more details.

```

I have no idea why it seems to be causing an issue with the first line

---

<div class="post-metadata">

**Author:** ![jayair](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/jayair/32/9_2.png) [@jayair](https://discourse.sst.dev/u/jayair)\
**Post date:** [September 28, 2019, 6:31pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/10 "2019-09-28T18:31:00Z")

</div>

Hmm I think you might be using an older version of the starter project? Can you compare your `package.json` to the one in the demo repo?

> <https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/package.json>

---

<div class="post-metadata">

**Author:** ![Jimcumming](https://avatars.discourse-cdn.com/v4/letter/j/7bcc69/32.png) [@Jimcumming](https://discourse.sst.dev/u/Jimcumming)\
**Post date:** [October 9, 2019, 10:43am UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/11 "2019-10-09T10:43:30Z")

</div>

I seem to be having some trouble running the unit tests. When running npm test I get the following error.

```
  SyntaxError: Cannot use import statement outside a module

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

```

This is running node 12.11.1 on Windows 10. Package.json is as follows:

```
{
  "name": "notes-app-api",
  "version": "1.1.0",
  "description": "A Node.js starter for the Serverless Framework with async/await and unit test support",
  "main": "handler.js",
  "scripts": {
"test": "jest"
  },
  "author": "",
  "license": "MIT",
  "repository": {
"type": "git",
"url": "https://github.com/AnomalyInnovations/serverless-nodejs-starter.git"
  },
  "devDependencies": {
"aws-sdk": "^2.545.0",
"jest": "^24.9.0",
"serverless-bundle": "^1.2.5",
"serverless-dotenv-plugin": "^2.1.1",
"serverless-offline": "^5.3.3"
  },
  "dependencies": {
"stripe": "^7.10.0",
"uuid": "^3.3.3"
  }
}

```

Any ideas?

---

<div class="post-metadata">

**Author:** ![Jimcumming](https://avatars.discourse-cdn.com/v4/letter/j/7bcc69/32.png) [@Jimcumming](https://discourse.sst.dev/u/Jimcumming)\
**Post date:** [October 9, 2019, 4:01pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/12 "2019-10-09T16:01:28Z")

</div>

I’m also hitting problems when I try to deploy using Seed. Logged error is

````
```
    /tmp/seed/source/tests/billing.test.js:1
```

```
    ({"Object.<anonymous>":function(module,exports,require, __dirname,__ filename,global,jest){import { calculateCost } from "../libs/billing-lib";
```

```
                                                                                                    ^
```

```

```

```
    SyntaxError: Unexpected token {
```

```

```

```
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
```

```
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
```

````

and

````
```
ERROR: FAIL tests/billing.test.js
```

```
ERROR: ● Test suite failed to run
```

```
ERROR: 
```

```
ERROR: Jest encountered an unexpected token
```

```
ERROR: 
```

```
ERROR: This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
```

```
ERROR: 
```

```
ERROR: By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
```

```
ERROR: 
```

```
ERROR: Here's what you can do:
```

```
ERROR: • To have some of your "node_modules"
```
````

---

<div class="post-metadata">

**Author:** ![jayair](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/jayair/32/9_2.png) [@jayair](https://discourse.sst.dev/u/jayair)\
**Post date:** [October 9, 2019, 8:43pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/13 "2019-10-09T20:43:21Z")

</div>

Hmm you might be using an older version of the tutorial. The test command should be using `serverless-bundle test` instead.

> <https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/package.json#L7>

---

<div class="post-metadata">

**Author:** ![Jimcumming](https://avatars.discourse-cdn.com/v4/letter/j/7bcc69/32.png) [@Jimcumming](https://discourse.sst.dev/u/Jimcumming)\
**Post date:** [October 10, 2019, 8:35am UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/14 "2019-10-10T08:35:06Z")

</div>

That seems to have done the trick. I was halfway through the tutorial when you released the node 8 \> 10 update. Started again from scratch but it must have cached something somewhere.

Thanks for the help and thank you for creating such a great tutorial series.

---

<div class="post-metadata">

**Author:** ![jayair](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/jayair/32/9_2.png) [@jayair](https://discourse.sst.dev/u/jayair)\
**Post date:** [October 10, 2019, 11:41am UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/15 "2019-10-10T11:41:45Z")

</div>

Glad you figured it out!

---

<div class="post-metadata">

**Author:** ![kristibyrnes](https://avatars.discourse-cdn.com/v4/letter/k/7ba0ec/32.png) [@kristibyrnes](https://discourse.sst.dev/u/kristibyrnes)\
**Post date:** [October 16, 2019, 7:21pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/16 "2019-10-16T19:21:57Z")

</div>

This worked for me, great idea!

---

<div class="post-metadata">

**Author:** ![jayair](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/jayair/32/9_2.png) [@jayair](https://discourse.sst.dev/u/jayair)\
**Post date:** [November 3, 2019, 1:27am UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/18 "2019-11-03T01:27:46Z")

</div>

Hmm that page doesn’t have the line you are talking about?

---

<div class="post-metadata">

**Author:** ![amoses12](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/amoses12/32/675_2.png) [@amoses12](https://discourse.sst.dev/u/amoses12)\
**Post date:** [November 21, 2019, 6:26pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/19 "2019-11-21T18:26:59Z")

</div>

I know this is an old thread, but you’ve been super helpful in the past and I can’t seem to find any information on what I’m trying to do with unit testing. My question is, “How do I unit test a serverless lambda function with DB calls when there’s no connection to the DB before it’s been deployed?”. Example:

```
export async function getResources(){
    const resources = await db('resources')
    .select('resources.firstname, 'resources.lastname');

    //do something with the object returned

return resources;
}

```

In this case, I’d like to test what I’m doing with the returned object(which would be where the comment is), but need to somehow get the test to skip the db call and replace it with mock data we’ve created and check the result. Any tips would be greatly appreciated. Thanks!

---

<div class="post-metadata">

**Author:** ![boxabirds](https://avatars.discourse-cdn.com/v4/letter/b/c57346/32.png) [@boxabirds](https://discourse.sst.dev/u/boxabirds)\
**Post date:** [December 13, 2019, 4:07pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/20 "2019-12-13T16:07:36Z")

</div>

I’ve only used Python for this stuff before so I’m new to the Javscript AWS world. But a little bit of looking around and maybe this article can help: it [mocks out the AWS SDK for JavaScript](https://medium.com/@windix/mock-aws-javascript-library-in-jest-8aad872c1468)

---

<div class="post-metadata">

**Author:** ![boxabirds](https://avatars.discourse-cdn.com/v4/letter/b/c57346/32.png) [@boxabirds](https://discourse.sst.dev/u/boxabirds)\
**Post date:** [December 13, 2019, 4:26pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/21 "2019-12-13T16:26:45Z")

</div>

I still had problems with that error today. I dug around and learnt a little about ECMAScript modules. If you create another `package.json` inside `test/` and say it’s a module, it works for me:

`tests/package.json`

```
{
  "type": "module"
}

```

Output:

```
(serverless-stack) bash-3.2$ npm test

> notes-app-api@1.1.0 test /Users/julian/learn/serverless-stack/notes-app-api
> serverless-bundle test

 PASS tests/billing.test.js
  ✓ Lowest tier (3ms)
  ✓ Middle tier
  ✓ Highest tier (1ms)

Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 1.636s, estimated 2s
Ran all test suites.
```

---

<div class="post-metadata">

**Author:** ![leonct](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.sst.dev/leonct/32/746_2.png) [@leonct](https://discourse.sst.dev/u/leonct)\
**Post date:** [January 9, 2020, 2:45pm UTC](https://discourse.sst.dev/t/unit-tests-in-serverless/173/22 "2020-01-09T14:45:15Z")

</div>

Great tutorial, thank you!

Any idea how I could use jest or any other testing library to test one API Gateway endpoint protected by Cognito?

As an extra level of security, I’m using CognIto Identity Id as param to post data in DynamoDB and so to prevent a malicious user with access in the same pool to post data on behalf of an other user, but I could not really figure out how to test it.

Here an example of DynamoDb param I’m using to update user data:

```auto
const params = {
    TableName: "products",
    Key: {
      userId: event.requestContext.identity.cognitoIdentityId,
      productId: event.pathParameters.productId
    },

```

[Next page](https://discourse.sst.dev/t/unit-tests-in-serverless/173.md?page=2)
