TypeError:Cannot read properties of undefined(阅读“roomType”),Test API jest,node.js,prisma

bxgwgixi  于 2023-11-17  发布在  Node.js
关注(0)|答案(1)|浏览(234)

我试图测试我的API使用jest和它不工作,同时在 Postman 它的作品成功.这里是我的服务代码:

async function createData(req, res) {
    const newData = req.body

    const data = await prisma.room.create({
        data: {
            roomType: newData.roomType,
            roomImage: newData.roomImage,
            roomStatusId: newData.roomStatusId,
            roomCode: newData.roomCode,
            roomCapacityId: newData.roomCapacityId,
            category: newData.category,
            floor: newData.floor,
            i: newData.i,
            occupied_status: newData.occupied_status,
            overlook: newData.overlook,
            description: newData.description,
            bedSetup: newData.bedSetup,
            connecting: newData.connecting,
            rateCodeId: newData.rateCodeId
        }
    });

    if (!data) {
        return errorResponse(res, 'Error', '', 404);
    }

    return successResponse(
        res,
        `Data has been inserted successfully`,
        data,
        200,
    );
}

字符串
下面是我的API测试代码:

describe('POST /room', () => {
    it('Should create a new room', async () => {
        const newData = {
            roomType: "STANDARD",
            roomImage: "https://i.pravatar.cc/300",
            roomStatusId: 1,
            roomCode: 1,
            roomCapacityId: 1,
            category: "well",
            floor: 3,
            i: 2,
            occupied_status: true,
            overlook: "well",
            description: "kamar well",
            bedSetup: "well",
            connecting: "well",
            rateCodeId: 1
        };
        // console.log('createdRoom:', newData);

        const response = await request(app)
            .post('/room')
            .send(newData);

        // Perform assertions
        expect(response.statusCode).toBe(200);
        expect(response.body).toHaveProperty('data');
        expect(response.body.data).toMatchObject(newData);
    });
});


错误代码:

FAIL  __tests__/apis/room.api.test.js (9.585 s)
  ● POST /room › Should create a new room

    TypeError: Cannot read properties of undefined (reading 'roomType')

      40 |     const data = await prisma.room.create({
      41 |         data: {
    > 42 |             roomType: newData.roomType,
         |                               ^
      43 |             roomImage: newData.roomImage,
      44 |             roomStatusId: newData.roomStatusId,
      45 |             roomCode: newData.roomCode,

      at roomType (src/services/room.service.js:42:31)
      at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
      at next (node_modules/express/lib/router/route.js:144:13)
      at Route.dispatch (node_modules/express/lib/router/route.js:114:3)
      at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
      at node_modules/express/lib/router/index.js:284:15
      at Function.process_params (node_modules/express/lib/router/index.js:346:12)
      at next (node_modules/express/lib/router/index.js:280:10)
      at Function.handle (node_modules/express/lib/router/index.js:175:3)
      at router (node_modules/express/lib/router/index.js:47:12)
      at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
      at trim_prefix (node_modules/express/lib/router/index.js:328:13)
      at node_modules/express/lib/router/index.js:286:9
      at Function.process_params (node_modules/express/lib/router/index.js:346:12)
      at next (node_modules/express/lib/router/index.js:280:10)
      at expressInit (node_modules/express/lib/middleware/init.js:40:5)
      at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
      at trim_prefix (node_modules/express/lib/router/index.js:328:13)
      at node_modules/express/lib/router/index.js:286:9
      at Function.process_params (node_modules/express/lib/router/index.js:346:12)
      at next (node_modules/express/lib/router/index.js:280:10)
      at query (node_modules/express/lib/middleware/query.js:45:5)
      at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
      at trim_prefix (node_modules/express/lib/router/index.js:328:13)
      at node_modules/express/lib/router/index.js:286:9
      at Function.process_params (node_modules/express/lib/router/index.js:346:12)
      at next (node_modules/express/lib/router/index.js:280:10)
      at Function.handle (node_modules/express/lib/router/index.js:175:3)
      at Function.handle (node_modules/express/lib/application.js:181:10)
      at Server.app (node_modules/express/lib/express.js:39:9)

  ● POST /room › Should create a new room

    thrown: "Exceeded timeout of 5000 ms for a test.
    Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."

      24 | });
      25 | describe('POST /room', () => {
    > 26 |     it('Should create a new room', async () => {
         |     ^
      27 |         const newData = {
      28 |             roomType: "STANDARD",
      29 |             roomImage: "https://i.pravatar.cc/300",

      at it (__tests__/apis/room.api.test.js:26:5)
      at Object.describe (__tests__/apis/room.api.test.js:25:1)

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
Test Suites: 1 failed, 2 passed, 3 total
Tests:       1 failed, 8 passed, 9 total
Snapshots:   0 total
Time:        10.968 s
Ran all test suites.


我试过使用 Postman ,它没有错误,我不知道为什么'房间类型'是未定义的。

lyfkaqu1

lyfkaqu11#

奇怪的是,它似乎通过 Postman 工作,而不是在测试中。
我已经设置了一个最小的例子来解决你的问题,但看起来效果不错。很可能你的解析器配置不正确,请参阅app.use(express.json())
下面是一个工作示例(也在StackBlitz上):

const request = require('supertest');
const express = require('express');

const initializeMockApp = () => {
  const app = express();
  app.use(express.json());

  app.post('/room', (req: any, res: any) => {
    const newData = req.body;

    const data = {
      roomType: newData?.roomType,
    };

    res.status(200).json(data);
  });
  return app;
};

describe('MockApp', () => {
  it('POST /room', async () => {
    // given
    const app = initializeMockApp();
    const newData = { roomType: 'my-room-type' };

    // when
    const res = await request(app).post('/room').send(newData);

    // then
    expect(res.statusCode).toBe(200);
    expect(res.body.roomType).toEqual(newData.roomType);
  });
});

字符串

相关问题