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

How to fix Expected value: "1" Received array: [{"COUNT (*)": "1"}] error in TypeORM with jest framework

我是 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"}]

您正在运行通过 TypeORMs API 进行原始查询。当您 运行 原始查询时,TypeORM 将 return 原始结果,在这种情况下是来自您的 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);