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

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

The absence of typings.json in Typescript is creating an issue

As of now, I am encountering the following error during compilation: typings.json is missing In my existing packages.json, I have included the following dependency: "devDependencies": { "typescript": "^2.6.1", ... } Do you have any suggestion ...

What are some best practices for integrating ES2020 into an Angular project?

Below is the content of my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap&q ...

What steps are required to customize a pre-existing DevExtreme JQuery DataGrid that was initially built in a cshtml file using Typescript?

I'm currently developing a web application using DevExtreme JQuery. Within the frontend, I have set up a DataGrid in a cshtml file. With DevExtreme functionality, it's possible to include an Add Button to the DataGrid that triggers a popup for in ...

At what point does the constructor of an injected service in Angular execute?

When using @Injectable({providedIn: 'root'}) in Angular 7 for a service, the constructor of the service executes when exactly? Is it upon the creation of a component that utilizes it as a dependency or does it wait until a method within the servi ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

Deactivating attribute inheritance / configuring component settings with script setup and Typescript

Is there a way to disable attribute inheritance for a component's options when using script setup syntax with Typescript in Vue 3? Here is the JavaScript code example: app.component('date-picker', { inheritAttrs: false, // [..] }) How ...

What is the best way to determine if several simultaneous tasks have been completed?

Implementing multiple parallel actions in an Angular component has proven to be challenging for me. Following each action (foo), I subscribe to its result. I've been attempting to determine if any actions are currently running or have completed using ...

Dealing with compilation errors in TypeScript

I'm working on a simple TypeScript program that looks like this - const users = [{ name: "Ahmed" }, { name: "Gemma" }, { name: "Jon" }]; // We're trying to find a user named "jon". const jon = users.find(u => u.name === "jon"); However, wh ...

Dealing with Overwhelmingly Large Angular 5 Components

I'm currently developing a project in Angular 5 and one of our component files is becoming quite large, reaching nearly a thousand lines and continuing to grow. This will eventually make it difficult to manage and understand. We are seeking advice on ...

The binding element 'dispatch' is assumed to have the 'any' type by default. Variable dispatch is now of type any

I came across this guide on implementing redux, but I decided to use TypeScript for my project. Check out the example here I encountered an issue in the AddTodo.tsx file. import * as React from 'react' import { connect } from 'react-redux ...

Ways to implement logging in an NPM package without the need for a specific logging library

Currently, I am in the process of developing a company npm package using TypeScript and transferring existing code to it. Within the existing code, there are instances of console.log, console.warn, and console.error statements, as shown below: try { c ...

What steps should I take to fix the Typescript error showing up in my Next.js route?

import type { NextApiRequest, NextApiResponse } from "next"; import db from "../../app/libs/dbConn"; interface DataProps { auth: [ { name?: string; email?: string; passwordHash?: string; } ]; status: n ...

Slideshow through each item using Typescript and Angular8

I came across a solution in this carousel on by one link, but I'm struggling to work with the jQuery code even though I have JQuery installed in my project. For example: const next = jQuery(this).next(); I am looking to convert the JQuery code from ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

Subscription to Observable content failed to run

When a submit button is clicked inside the component HTML, it triggers a function called addCollaborators(). The code for this function can be found below: component.ts emails: string[] = []; constructor(public userService: UserService) {} // Function ...

What is the process for generating a dynamic array in typescript?

Looking to create a TypeScript dynamic array with the desired format: const display = [ { id: 1, displayName: "Abc1" }, { id: 2, displayName: "Abc2" }, { id: 3, displayName: "Abc3" } ] Attempted the following code ...

I am attempting to retrieve custom cellRendererParams within the CustomCellRenderer class

I'm currently working with Ag-Grid in my angular application and am trying to implement a custom cell renderer. The tutorial I followed uses ICellRendererParams for the parameter type passed to the init event. agInit(params: ICellRendererParams): void ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

Encountering the error message "String length is invalid" during the execution of ng build for a library

While working with Angular and attempting to build a large library using the command ng build <project>, we encountered the following issue: ❌ Generating "fesm2015" Invalid string length The build for fesm2020 was successful, but the sourcem ...