What are the steps to execute jest in an AWS Lambda environment?

I'm looking to execute my end-to-end test post-deployment for the ability to revert in case of any issues. I've followed the guidelines outlined in this particular blog post.

Below is my lambda function:

export async function testLambda(event: APIGatewayEvent, context, callback) {
    console.log('Initial version!')
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            message: 'Initial version!'
        })
    }
    return callback(null, response)
}

This is my post-hook logic:

export async function postHook(event, context, callback) {

    const deploymentId = event.DeploymentId;
    const lifecycleEventHookExecutionId = event.LifecycleEventHookExecutionId;
    console.log(`deploymentId: ${deploymentId} - lifecycleEventHookExecutionId: ${lifecycleEventHookExecutionId}`)
    try {
        const jest = require('jest');
        require('ts-jest');
        const options = {
        projects: [__dirname],
        silent: true,
        };

        await jest.runCLI(options, options.projects);
            // update AWS deployment for success
        } catch (err) {
            // update AWS deployment for failure
            console.log(err);
            return { statusCode: 500 }
    }
}

My tests are written in TypeScript and I have included my jest.config.js and tsconfig.json in the serverless application zip file. However, I am facing an issue where global symbols like describe and expect from jest are not being recognized:

Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try npm i @types/jest or npm i @types/mocha and then add jest or mocha to the types field in your tsconfig.

What would be the best approach to run my tests using AWS Lambda? Currently, my only options seem to be triggering another task like CodeBuild to run the tests or switching to a different testing framework like Mocha. Is there a more optimal solution available?

Answer №1

By default, Jest includes describe, test, and other functions in the global context. However, when running Jest programmatically, these functions are not automatically added to the global scope. To use them, you need to explicitly import them from '@jest/globals'.

import { describe, test} from '@jest/globals';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated. I have searched extensively bu ...

Is there a way to access the badge hidden behind the collapsible menu in bootstrap 4?

After moving from bootstrap 3 to bootstrap 4, my items no longer align properly. I've scoured the entire Internet for a solution, but I've run out of options (and patience.. haha) This is how it currently looks: I want the badge to be positione ...

Unexpectedly, a significant ngrx createEffect leads to an unusual error following an update, but the issue vanishes when certain code snippets like tap or filter are disabled

I have been in the process of upgrading a massive Angular 12 project to Angular 13 and have completed several steps. One significant change was the rewriting of Effects using a newer approach like createEffect(() => instead of @Effect However, during ...

How can I pass an array of string inputs into Vue 3?

Working with Vue 3, I'm setting up a form that will display text input fields corresponding to a fixed-length array of strings. Each field's v-model should connect to the respective string in the array. Here is my current code snippet for the vie ...

Issue with accessing custom method in subclass in Typescript

Recently delving into TypeScript, I decided to subclass Error and add a new method called getCode() in my MyError class. export class MyError extends Error { public code: number; constructor(code: number, message?: string) { super(mes ...

Connecting RxJS Observables with HTTP requests in Angular 2 using TypeScript

Currently on the journey of teaching myself Angular2 and TypeScript after enjoying 4 years of working with AngularJS 1.*. It's been challenging, but I know that breakthrough moment is just around the corner. In my practice app, I've created a ser ...

Troubleshooting import errors with Typescript for C3 and D3 libraries

I have recently started working on a project using the C3 graphing library within an Ionic2/Angular2 TypeScript setup. After installing C3 via npm and the type definitions via tsd, I imported it into my own TypeScript file like this: import {Component} fr ...

The Angular tutorial for the "Tour of Heroes" is experiencing issues with aligning the heroes' list properly

I am currently working on the Angular tour of heroes tutorial. However, I am facing an issue when trying to display the list of heroes as it appears like this: It is strange because even though the CSS/HTML/TS code from the tutorial seems correct, the lis ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...

Is there a way to ensure that the return type of a generic function is always optional in Typescript?

Is there a way to ensure the return type is always optional from a generic return type in functions? I specifically need the return types (data & error) to be optional at all times since one of them will always be undefined. TypeScript declarations i ...

What is the best way to skip the additional step of "Sign In With Cognito" in next-auth and go straight to the sign-in form?

When working on my Next.js project and utilizing Cognito for sign-in through the next-auth library, I encounter a initial step where I have to click a button labeled "Sign in with Cognito" before being directed to the actual sign-in form. Is there a way to ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

Within Angular, the Subscribe function is invoked after all other methods in the component have been executed. Consequently, this sequence of events often prevents me from effectively utilizing the response data

Struggling with implementing await and async in TypeScript, especially as a beginner. Below is how I attempted to use them: async refreshList(){ await this.service.refreshList().subscribe(res => { console.log(res); this.service.todoListModel=res; ...

Using the Moment library in a NestJS application

I am integrating momentjs into my nestjs application and I want to ensure that my services can be tested effectively. To achieve this, I have included momentjs in my module setup as shown below: providers: [ { provide: 'MomentWrapper', ...

Error: The type 'boolean | (() => void)' cannot be assigned to type 'MouseEventHandler<HTMLButtonElement> | undefined'

Playing audio in a NextJS app while writing code in TypeScript has been an interesting challenge. The onClick() function performs well in the development environment, triggered by npm run dev. <button onClick ={toggle}> {playing ? "Pause" : ...

Using Angular to access HTML content through the .ts file

Is there a way to retrieve the value of the input field [newUser] when clicking on the button and executing the action [onAddUser()] in the .ts file? <input type="text" ng-model="newUser" style="text-align:center"/> <button (cl ...

What could be the reason for my difficulties in retrieving the necessary data from this website with Selenium?

Basically, I've been struggling to interact with the "enter your address" field on a particular website through xpath and selenium. I'm curious as to why this is happening. Detailed Explanation The website in question is this one. It features a ...

Is it possible to use conditional logic on child elements in formkit?

I am a bit confused about how this process functions. Currently, I am utilizing schema to create an address auto complete configuration. My goal is to have the option to display or hide the fields for manual input. This is the current appearance of the ...

How can we include additional types for external npm packages in a React TypeScript project?

Recently, I encountered an issue while using the react-microsoft-login package from npm. I included a button in the children property and received a typescript error stating that "property 'children' does not exist on type 'intrinsicattribut ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...