Dealing with enum values in Jest tests when using Prisma can be tricky. The error message "Group[] not assignable to

Here is an example of my prisma postgresql schema:

model User {
  id         Int          @id @default(autoincrement())
  uuid       String       @db.Uuid
  createdat DateTime     @default(now()) @db.Timestamp(6)
  updatedat DateTime     @updatedAt
  firstname String       @db.VarChar
  lastname  String       @db.VarChar
  email      String       @unique @db.VarChar
  password   String       @db.VarChar
  group      Group[]
}

enum Group {
  USER
  ADMIN
}

Now, let's take a look at the jest test I wrote:

/* eslint-disable no-unused-vars */
import { create } from '../index';
import { prismaMock } from '../../../../../db/singleton';

enum Group {
  USER,
  ADMIN,
}

// code snippet
/*enum Group {
  USER = 'USER',
  ADMIN = 'ADMIN',
}*/


test('should create new user ', async () => {
  try {
    const userModel = {
      id: 1,
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b232e2727240b3b392238262a">[email protected]</a>',
      uuid: '65sdf5sa4dfs5sdf54ds5f',
      createdat: new Date(),
      updatedat: new Date(),
      firstname: 'jon',
      lastname: 'doe',
      password: '123456',
      group: [Group.USER],
    };

    const demoUser = {
      id: 1,
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f272a2323200f3f3d263c222e612620">[email protected]</a>',
      uuid: '65sdf5sa4dfs5sdf54ds5f',
      firstname: 'jon',
      lastname: 'doe',
      password: '123456',
      group: [Group.USER],
    };

    prismaMock.user.create.mockResolvedValue(userModel);

    await expect(create(demoUser)).resolves.toEqual({
      id: 1,
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543c3138383b1424263d2739357a3d3b">[email protected]</a>',
      uuid: '65sdf5sa4dfs5sdf54ds5f',
      createdat: new Date(),
      updatedat: new Date(),
      firstname: 'jon',
      lastname: 'doe',
      password: '123456',
      group: [Group.USER],
    });
  } catch (error) {
    console.log('*****', error);
  }
});

An error occurred when running the test:

Argument of type '{ id: number; email: string; uuid: string; createdat: Date; updatedat: Date; firstname: string; lastname: string; nickname: string; password: string; group: Group[]; }' is not assignable to parameter of type 'User | Prisma__UserClient<User>'.
  Type '{ id: number; email: string; uuid: string; createdat: Date; updatedat: Date; firstname: string; lastname: string; nickname: string; password: string; group: Group[]; }' is not assignable to type 'User'.
    Types of property 'group' are incompatible.
      Type 'Group[]' is not assignable to type 'import("/example/example-api/node_modules/.prisma/client/index").Group[]'.
        Type 'Group' is not assignable to type 'import("/example/example-api/node_modules/.prisma/client/index").Group'.ts(2345)

I am confused why Group[] cannot be assigned to type Group. In the userModel, I specified group: [Group.USER]. Since a user can belong to multiple groups, how should I handle this scenario in my typescript test?

Answer №1

It is recommended to utilize the enum type provided by Prisma instead of creating your own. Simply import the enum directly like so:

import { Group } from '@prisma/client';

const userModel = {
      id: 1,
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1078757c7c7f50606279637d713e797f">[email protected]</a>',
      uuid: '65sdf5sa4dfs5sdf54ds5f',
      createdat: new Date(),
      updatedat: new Date(),
      firstname: 'jon',
      lastname: 'doe',
      password: '123456',
      group: [Group.USER],
};

Answer №2

While running my Jest Tests, I encountered a strange error:

 TypeError: Cannot read properties of undefined

To resolve this issue, I made a slight adjustment to the code like so:

import { Group } from 'prisma/schema'

const valuePayload = {
  resource: "USER" as Group
}

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

How do Angular and NestJS manage to dynamically resolve injection tokens during runtime using the TypeScript type hints provided at compile time?

Frameworks such as Angular and NestJS in TypeScript utilize dependency injection by converting TypeScript type hints into injection tokens. These tokens are then used to fetch dependencies and inject them into constructors at runtime: @Injectable() // < ...

How can I dynamically generate multiple Reactive Forms from an array of names using ngFor in Angular?

I am in the process of developing an ID lookup form using Angular. My goal is to generate multiple formGroups within the same HTML file based on an array of values I have, all while keeping my code DRY (Don't Repeat Yourself). Each formGroup will be l ...

Typescript feature: Configuring BaseUrl with nested directories

When utilizing the 'baseUrl' property along with the 'paths' property in this manner: "baseUrl": "./src", "paths": { "app-component": [ "app/app.component"], "test-component": [ "app/test/test.component" ] } the compilation proces ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

How can the values from the scale [-60, -30, -10, 0, 3, 6, 10] be converted to a decimal range of 0-1 through

Thank you for helping me with so many of my issues. <3 I'm certain that someone has already solved this, but I'm unsure of the specific mathematical term (I've attempted reverse interpolation and others, but with no luck) so I am present ...

Maximize the benefits of using React with Typescript by utilizing assignable type for RefObject

I am currently working with React, Typescript, and Material UI. My goal is to pass a ref as a prop. Within WidgetDialog, I have the following: export interface WidgetDialogProps { .... ref?: React.RefObject<HTMLDivElement>; } .... <div d ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

Tips for effectively sharing custom validators across different modules

After creating a password validator based on a tutorial, I attempted to use it on multiple forms within different parts of my application. However, I encountered an error stating: Type PasswordValidator is part of the declarations of 2 modules: SignupMod ...

Each property of an object has its own unique key, yet they all share the same data type

I have a single-use object with only three properties, all of which should be of the same type. The code below currently achieves this, but I'm curious if there is a more efficient way to declare the type for timingsObject: let timingsObject: ...

Can you determine the size of an unknown array in TypeScript?

Currently diving into TypeScript and tackling some TDD challenges. Within my model file, I'm working with a property named 'innovatorQuotes' that should be an array containing strings with a fixed length of 3. I'm struggling to nail dow ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

Can classes be encapsulated within a NgModule in Angular 2/4?

Looking to organize my classes by creating a module where I can easily import them like a separate package. Take a look at this example: human.ts (my class file) export class Human { private numOfLegs: Number; constructor() { this.numOfLegs = 2 ...

Determine the presence or absence of data in an Angular Observable

Here is an example of how I am making an API call: public getAllLocations(): Observable<any> { location = https://v/locations.pipe(timeout(180000)); return location; } In my appl ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

What is the procedure for renaming an item within a basic array in Angular?

I am working on a project in Angular and have constructed an array. I am now looking to change the name of one of the items in this array. While I have figured out how to rename keys in an array, I'm still unsure about how to do so for its values. ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...