Experimenting with throws using Jest

One of the functions I'm testing is shown below:

export const createContext = async (context: any) => {
  const authContext = await AuthGQL(context)
  console.log(authContext)
  if(authContext.isAuth === false) throw 'UNAUTHORIZED'
  return authContext
}

I am currently testing this function as follows:

describe('Testing Apollo service file', () => {
  beforeAll(async () => {
    await mongoConnect()
  })

  test('test apollo context setup and configuration', () => {
    const mockContext = {
      req: {
        headers: {
          
        }        
      }

    } as ExpressContext

    expect(() => createContext(mockContext)).toThrow()
  })

  afterAll(async () => {
    await mongoDisconnect()
  })
})

The beforeAll and afterAll calls are simply connecting and disconnecting from a local database for testing purposes. The mockContext being passed intentionally has missing fields to trigger an 'UNAUTHORIZED' error in the createContext function.

After running the test, the terminal output is as follows:

https://i.sstatic.net/XB4t5.png

UPDATE:

In accordance with Jest documentation and further testing: https://jestjs.io/docs/using-matchers, I wrote another function that throws an error and tested it using the following line:

// test sync function
function compileAndroidCode() {
  throw new Error('UNAUTHORIZED');
}

// Expect function that tests the thrown error
expect(() => compileAndroidCode()).toThrow('UNAUTHORIZED')

It seems there might be some syntax issues related to the async/await functionality in my test.

Answer №1

If you have an async function, make sure to use the await keyword. Here is how you can implement it:

  test('test setting up and configuring apollo context', async () => {
    const fakeContext = {
      req: {
        headers: {

        }
      }

    } as ExpressContext

   await expect(createCustomContext(fakeContext)).rejects.toThrow()
  })

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

Tips for creating a unit test case for a specialized validator in angular reactive forms

Looking for guidance on creating a test case for this specific method: export class CustomErrorStateMatcher implements ErrorStatematcher { isErrorState(control: FormControl,form:NgForm | FormGroupDirective | null){ return control && control.inval ...

Is there a way to make an angular component reuse itself within its own code?

I am dealing with a parent and child component scenario where I need to pass data from the parent component to the child component. The aim is to display parentData.name in the child component when parentData.isFolder===false, and if parentData.isFolder=== ...

Specifying the type of "this" within the function body

After going through the typescript documentation, I came across an example that explains how to use type with this in a callback function. I am hoping someone can assist me in comprehending how this callback will operate. interface DB { filterUsers(fil ...

Steps to modify the CSS of a custom component in Angular 8

I have been attempting to override the css of a custom component selector, however, my attempts have been unsuccessful. I have tried using ":ng-deep" but it hasn't worked. How can I go about finding a solution for this issue? app.component.html: < ...

Utilize Lambda Layer to seamlessly share interfaces/types across Lambda Functions

I have a lambda layer file that contains an enum definition (which will be used in various lambda functions) as shown below: exports enum EventTypes { Create, Delete, Update, } Initially, everything was working well as I tested ...

JavaScript file encountering a Typescript issue with a property defined in a subclass

Currently, I am utilizing Typescript to validate my Javascript files. One issue I have encountered is that when I inherit from a class, Typescript does not recognize the types of the properties in the parent class. I am unsure if I am overlooking something ...

An uncommon token was found by Jest - import (Angular CLI 6)

Struggling to get jest installed and running in an angular/cli (v6) app on Mac. Despite trying various methods to set up jest, I keep encountering the following error: Test suite failed to run Jest encountered an unexpected token This usually me ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

What is the best way to restrict a Generic type within a Typescript Function Interface?

Imagine having the following interface definitions: interface SomeInterface {a: string; b: number} interface SomeFunction<T> {(arg: T) :T} The usage of the function interface can be demonstrated like this: const myFun: SomeFunction<string> = a ...

Utilize TypeScript enum keys to generate a new enum efficiently

I am in need of two Typescript enums as shown below: export enum OrientationAsNumber { PORTRAIT, SQUARE, LANDSCAPE } export enum OrientationAsString { PORTRAIT = 'portrait', SQUARE = 'square', LANDSCAPE = 'landscape&ap ...

TypeScript compilation will still be successful even in the absence of a referenced file specified using require

Having both Project 1 and Project 2 in my workspace, I encountered an unusual issue after copying a file, specifically validators/index.ts, from Project 1 to Project 2. Surprisingly, TypeScript compilation went through successfully without showing any erro ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

What is the proper way to define an array of objects in TypeScript?

In search of a way to define a function that accepts an array of unspecified object types, known as "anonymous types." I want to enforce strict typing with TypeScript. The objects in the array all have properties like name, price, and description. bagTotal ...

Utilize JSX attributes across various HTML elements

I'm looking for a solution to efficiently add JSX attributes to multiple elements. Here are the example attributes I want to include: class?: string; id?: string; style?: string; And here are the example elements: namespace JSX { interface Int ...

How can I pass properties from a childComponent to a parent component in Angular 2 without prior knowledge of the childComponent's class?

My main goal is to accomplish the following : I currently have a component setup like this: import { Component, Output, EventEmitter, OnInit } from '@angular/core'; @Component({ selector: 'like', template: '<p>this is ...

Encountering an error while testing a Vue component with v-dialog in Vitest: TypeError - globalStack.at is not a function

I've set up a vue project with vuetify and vitest. When running unit tests using happy-dom (also tried jsdom), everything works fine unless my component contains a v-dialog component, in which case I encounter the following error: TypeError: globalSta ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

Pass values between functions in Typescript

Currently, I have been working on a project using both Node JS and Typescript, where my main challenge lies in sharing variables between different classes within the same file. The class from which I need to access the max variable is: export class co ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...

The utilization of React.Component inheritance in TypeScript

In my attempt to develop a base class using React.Component and derive two classes from the base class, I have encountered an issue. Here is how I structured the classes: interface BaseItemProps { base_prop: string; } class BaseItem<P, T> exten ...