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:

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

Angular 2 - Ensuring service executes only when boolean condition is met

I am currently dealing with a navigation menu that utilizes the ng2-page-scroll module. When scrolling through the page using hashtag links, I encountered an issue. If I navigate across routes, there is a delay in loading the data. As a result, the servic ...

I seem to be missing some properties in the request body schema. Why am I receiving an incomplete model for

Seeking assistance in grasping the working of models in loopback4. Here's a model I defined: @model() export class ProductViewConfig extends BaseConfig { @property({ type: 'string', id: true, generated: true, }) _id?: strin ...

Encountered an issue while attempting to authenticate CMS signature using pkijs

I am attempting to validate a CMS signature generated with open ssl using the following command: $ openssl cms -sign -signer domain.pem -inkey domain.key -binary -in README.md -outform der -out signature Below is my code utilizing pkijs: import * as pkij ...

Incorporate an image icon into an Angular grid

Currently, I am in the process of building a web application using Angular. The main goal is to create a grid and color specific cells based on data input. Below is the snippet of my HTML code: <mat-grid-list cols="10"> <mat-grid-tile * ...

Exploring the integration of an Angular 4 application with Visual Studio 2017 using dot net core. Techniques for accessing configuration keys from appsetting.json in a TypeScript

I'm currently working on an Angular 4 application using Visual Studio 2017 with .NET Core. I need to figure out how to access configuration keys from appsetting.json in my TypeScript file. I know how to do it in the startup.cs file, but I'm strug ...

Issues arise when attempting to include the src attribute within the template tag in a Vuejs and Laravel project

After starting a project with Vuejs and Laravel using Laravel Mix, I encountered an issue. When attempting to split my component into separate files and load them in the .vue file as follows: <template src="./comp.html"></template> &l ...

The issue with the antd Input component's onChange event not updating state correctly when using a list fetched from an axios get request in a React

Recently delving into React, I've dedicated the past week to honing my skills. My current project involves creating a straightforward application featuring a 'product create' form alongside a product list equipped with a search bar (utilizin ...

What is the best approach to re-establish a websocket connection in TypeScript?

Encountering an issue when trying to add a "retry()" method: ERROR in src/app/films.service.ts(28,20): error TS2339: Property 'retry' does not exist on type 'WebSocketSubject'. this.wsSubject.retry().subscribe( (msg) => this. ...

Convert a regular element into a DebugElement within an Angular framework

Recently, I was working on testing an Angular Component which was going smoothly until I encountered a challenging issue that has been perplexing me for days. My main objective was to test whether the method "ajouterCompteurALaCampagne" is being called whe ...

Implementing a Map in Typescript that includes a generic type in the value

Here is a code snippet I am working with: class A<T> { constructor(public value: T) {} } const map = new Map(); map.set('a', new A('a')); map.set('b', new A(1)); const a = map.get('a'); const b = map.get(& ...

Retrieve the name from the accordion that was clicked

Hey there, I have a simple accordion that is based on an API called "names". <div *ngFor="let item of showDirNames | async | filter: name; let i = index;"> <button class="accordion" (click)="toggleAccordian($event, i)&q ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

Is there a way to eliminate properties in typescript without relying on the option feature?

I am struggling with removing properties in TypeScript. type Person<GN> = { getName: GN extends never ? never : GN, } const foo = <GN>(person: Person<GN>) => person const first = foo({}) // This should work const second = fo ...

Why is it necessary for the required type of a function parameter to be able to be assigned to

From Optional to Required Type const testFunc = (func: (param: number) => void): void => { func(3); }; testFunc((a?: number) => { console.log(a); }); From Required to Optional Type const testFunc = (func?: (param: number) => void): void = ...

Typescript has a knack for uncovering non-existent errors

When I attempted to perform a save operation in MongoDB using Mongoose, the code I initially tried was not functioning as expected. Upon conducting a search online, I came across a solution that worked successfully; however, TypeScript continued to flag an ...

send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered s ...

The optimal time to register for events within the Vue lifecycle

Currently, I am developing a Vue2 component using vue-component that includes a subcomponent. Here is an example: <note :bus="bus" :itemId="selectedId"></note> The subcomponent contains the following code snippet: <textarea v-model="text" ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...