首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编写Jest模拟Prisma数据库时遇到的问题

编写Jest模拟Prisma数据库时遇到的问题
EN

Stack Overflow用户
提问于 2022-07-10 14:50:30
回答 1查看 474关注 0票数 0

我有两个需要在代码中交互的数据库。我有一个简单的函数,它接受一个对象并使用Prisma将它写入我的PostgreSQL数据库。我已经用Postman测试了这个函数,它运行得很好,但是当我尝试使用Jest模拟(使用在Prisma单元测试指南中找到的单例模式)执行它时,它返回未定义的指示它没有与数据库交互并创建新记录。这是我的密码:

/prisma/临床-方案

代码语言:javascript
复制
generator client {
  provider = "prisma-client-js"
  output   = "./generated/clinical"
}

datasource clinicalDatabase {
  provider = "postgresql"
  url      = "postgresql://postgres:postgres@localhost:5432/clinical-data?schema=public"
}

model pcc_webhook_update {
  id                  Int                       @id @default(autoincrement())
  event_type          String
  organization_id     Int
  facility_id         Int
  patient_id          Int
  resource_id         String?
  webhook_date        DateTime                  @default(now()) @clinicalDatabase.Timestamptz(6)
  status              pcc_webhook_update_status @default(pending)
  status_changed_date DateTime?                 @clinicalDatabase.Timestamptz(6)
  error_count         Int                       @default(0)

  @@unique([organization_id, facility_id, patient_id, resource_id, event_type, status])
}

enum pcc_webhook_update_status {
  pending
  processing
  processed
  error
}

/prisma/临床-客户。

代码语言:javascript
复制
import { PrismaClient } from './generated/clinical';

const prismaClinical = new PrismaClient();

export default prismaClinical;

/检验/prisma-临床-模型

代码语言:javascript
复制
import { PrismaClient } from '../prisma/generated/clinical';
import { mockDeep, mockReset, DeepMockProxy } from 'jest-mock-extended';
import prisma from '../prisma/clinical-client';

jest.mock('../prisma/clinical-client', () => ({
  __esModule: true,
  default: mockDeep<PrismaClient>()
}));

beforeEach(() => {
  mockReset(prismaClinicalMock);
});

export const prismaClinicalMock = prisma as unknown as DeepMockProxy<PrismaClient>;

到目前为止,所有事情都遵循Prisma单元测试文档概述的约定。我所做的唯一的修改就是让它成为特定于数据库的东西。下面是我的功能和测试。handle-pcc-webhooks.ts中的请求对象是一个示例http请求对象,它的主体包含我关心的web钩子数据。

/函数/句柄-pcc-webhooks/handler.ts

代码语言:javascript
复制
import prismaClinical from '../../../prisma/clinical-client';
import { pcc_webhook_update } from '../../../prisma/generated/clinical';
import { requestObject } from './handler.types';

export const handlePccWebhook = async (request: requestObject) => {

  try {

    const webhook = JSON.parse(request.body);

    // if the webhook doesn't include a resource id array, set it to an array with an empty string to ensure processing and avoid violating
    // the multi-column unique constraint on the table
    const { resourceId: resourceIds = [''] } = webhook;

    let records = [];

    for (const resourceId of resourceIds) {

      // update an existing record if one exists in the pending state, otherwise create a new entry
      const record: pcc_webhook_update = await prismaClinical.pcc_webhook_update.upsert({
        where: {
          organization_id_facility_id_patient_id_resource_id_event_type_status: {
            organization_id: webhook.orgId,
            facility_id: webhook.facId,
            patient_id: webhook.patientId,
            resource_id: resourceId,
            event_type: webhook.eventType,
            status: 'pending'
          }
        },
        update: {
          webhook_date: new Date()
        },
        create: {
          event_type: webhook.eventType,
          organization_id: webhook.orgId,
          facility_id: webhook.facId,
          patient_id: webhook.patientId,
          resource_id: resourceId,
          status: 'pending' // not needed
        }
      });

      records.push(record);
    }

    return records;

  } catch (error) {

    console.error(error);
  }
};

/functions/handle-pcc-webhooks/handler.spec.ts

代码语言:javascript
复制
import fs from 'fs';
import path from 'path';
import MockDate from 'mockdate';
import { prismaClinicalMock } from '../../../testing/prisma-clinical-mock';
import { createAllergyAddRecord } from './__mocks__/allergy';
import { requestObject } from './handler.types';
import { handlePccWebhook } from './handler';

describe('allergy.add', () => {

  let requestObject: requestObject;
  let allergyAddRecord: any;

  beforeAll(() => {
    requestObject = getRequestObject('allergy.add');
  });

  beforeEach(() => {
    MockDate.set(new Date('1/1/2022'));
    allergyAddRecord = createAllergyAddRecord(new Date());
  });

  afterEach(() => {
    MockDate.reset();
  });

  test('should create an allergy.add database entry', async() => {

    prismaClinicalMock.pcc_webhook_update.create.mockResolvedValue(allergyAddRecord);

    // this is where I would expect handlePccWebhook to return the newly created database
    // record, but instead it returns undefined.  If I run the function outside of this
    // unit test, with the same input value, it functions perfectly
    await expect(handlePccWebhook(requestObject)).resolves.toEqual([allergyAddRecord]);
  });
});

// This just builds a request object with the current webhook being tested
function getRequestObject(webhookType: string) {

  // read the contents of request object file as a buffer, then convert it to JSON
  const rawRequestObject = fs.readFileSync(path.resolve(__dirname, '../../sample-data/handle-pcc-webhook-request.json'));
  const requestObject: requestObject = JSON.parse(rawRequestObject.toString());

  // read the contents of the webhook file as a buffer, then convert it to a string
  const rawWebhook = fs.readFileSync(path.resolve(__dirname, `../../sample-data/${webhookType}.json`));
  const webhookString = rawWebhook.toString();

  // set the body of the request object to the contents of the target webhook
  requestObject.body = webhookString;

  return requestObject;
}

最后,下面是运行单元测试的结果:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-11 02:22:18

所以几个小时后,我发现了这个问题。在我的handler.spec.ts文件中,我有以下一行:

代码语言:javascript
复制
prismaClinicalMock.pcc_webhook_update.create.mockResolvedValue(allergyAddRecord);

这样做的目的是模拟使用Prisma运行的任何create函数返回的值。问题是,我的函数使用的是upsert函数,我没有显式地模拟它,因此返回了未定义的函数。我把上面的行改为

代码语言:javascript
复制
prismaClinicalMock.pcc_webhook_update.upsert.mockResolvedValue(allergyAddRecord);

开始起作用了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72929391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档