如何修复预期值:“1”收到的数组:带有jest框架的TypeORM中的[{“COUNT(*)”:“1”}]错误

问题描述 投票:1回答:1

我是Jest框架和TypeORM的新手,我在运行manager.query语句时面临一个问题

我正在连接到数据库,而是使用查询构建器,我想使用实体管理器注入原始查询。下面是代码 -

import {createDBConnection} from "../utils/createDBConnection";

test(" Count", async () =>{
  jest.setTimeout(100000);
  const connection = await createDBConnection();
  const usercount= await connection.manager.query("SELECT COUNT (*) FROM User");
  expect(usercount).toContain('32');
});

以下是预期和实际产出。

expect(received).toContain(expected) // indexOf

    Expected value: "32"
    Received array: [{"COUNT (*)": "32"}]
typescript jestjs typeorm
1个回答
1
投票

您正在通过TypeORMs API运行原始查询。运行原始查询时,TypeORM将返回原始结果,在本例中是SQL服务器中的行数组。您需要解析结果以获得计数,例如:

const key = "user_count";
const usercount= await connection.manager.query(`SELECT COUNT (*) as ${key} FROM User`);
expect(usercount.length).toEqual(1);
expect(usercount[0][key]).toEqual("32");

或者,您可以使用存储库API来获取计数:

const usercount = await getRepository(User).count();
expect(usercount).toEqual(32);
© www.soinside.com 2019 - 2024. All rights reserved.