findAll()函数单元测试报错:expect深度相等匹配失败
关于findAll()单元测试的
expect(received).toEqual(expected)错误排查 错误现象
执行findAll()函数单元测试时,UsersService和UsersController的findAll测试用例均失败,测试结果显示收到空对象,与预期的用户对象不匹配,触发expect(received).toEqual(expected) // deep equality断言错误。
错误详情
PASS src/app.controller.spec.ts FAIL src/users/services/users.service.spec.ts ● UsersService › should return all users expect(received).toEqual(expected) // deep equality - Expected - 6 + Received + 1 - Object { - "birthDate": 2010-06-07T00:00:00.000Z, - "email": "xs@gsuj.lk", - "id": 2, - "name": "aq1s", - } + Object {} at src/users/services/users.service.spec.ts:68:38
FAIL src/users/controllers/users.controller.spec.ts (5.09 s) ● UsersController › should findall expect(received).toEqual(expected) // deep equality - Expected - 6 + Received + 1 - Object { - "birthDate": 2010-06-07T00:00:00.000Z, - "email": "xs@gsuj.lk", - "id": 2, - "name": "aq1s", - } + Object {} at src/users/controllers/users.controller.spec.ts:131:18
测试套件统计:3个失败,1个通过,共4个;测试用例:2个失败,9个通过,共11个。
相关代码
Users.controller.spec.ts
describe('UsersController', () => { let controller: UsersController; const mockUsersService = { create: jest.fn((dto) => { return { ...dto, }; }), update: jest.fn((id, dto) => ({ id, ...dto, })), delete: jest.fn((id) => ({ id, })), findAll: jest.fn((dto) => { return { ...dto, }; }), }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [UsersController], providers: [UsersService], }) .overrideProvider(UsersService) .useValue(mockUsersService) .compile(); controller = module.get<UsersController>(UsersController); }); it('should findall', async () => { const dto = { id: 2, name: 'aq1s', birthDate: new Date('2010-06-07'), email: 'xs@gsuj.lk', }; const data = await controller.findAll(); expect(data).toEqual({ id: dto.id, name: dto.name, birthDate: dto.birthDate, email: dto.email, }); }); });
user.service.spec.ts
describe('UsersService', () => { let service: UsersService; const mockUsersRepository ={ create:jest.fn().mockImplementation(dto =>dto), save:jest.fn().mockImplementation(user => Promise.resolve({id:2, ...user})), find:jest.fn().mockImplementation(() => ({})), } beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [UsersService, { provide:getRepositoryToken(User), useValue:mockUsersRepository, }, ], }).compile(); service = module.get<UsersService>(UsersService); }); it('should return all users', async () => { expect( await service.findAll()).toEqual({ id:2, name:'aq1s', birthDate: new Date('2010-06-07'), email : "xs@gsuj.lk" , }); }); });
users.service.ts
findAll(): Promise<User[]> { return this.userRepository.find() }
users.controller.ts
@Get() async findAll() { const users = await this.userService.findAll(); if (!users) { return 'error while finding users'; } return users; }
问题分析与修复方案
返回值类型不匹配:UsersService的findAll定义返回
Promise<User[]>(用户数组),但测试用例期望单个用户对象。- 修复:将测试用例中的预期值改为数组格式,比如
expect(await service.findAll()).toEqual([{ id:2, name:'aq1s', ... }]);同时确认Controller层的返回逻辑符合数组返回的预期。
- 修复:将测试用例中的预期值改为数组格式,比如
Mock仓库返回值错误:mockUsersRepository的find方法返回空对象
{},实际应返回用户数组。- 修复:修改mock的find方法,返回包含预期用户的数组:
find: jest.fn().mockImplementation(() => Promise.resolve([{ id:2, name:'aq1s', birthDate: new Date('2010-06-07'), email : "xs@gsuj.lk" }])),
- 修复:修改mock的find方法,返回包含预期用户的数组:
Controller测试中Mock服务未正确返回数据:UsersController测试里的mockUsersService.findAll方法依赖传入的dto参数,但实际调用时无传参,导致返回空对象
{}。- 修复:修改mockUsersService的findAll方法,直接返回预期的用户数组,无需依赖参数:
findAll: jest.fn(() => { return [{ id: 2, name: 'aq1s', birthDate: new Date('2010-06-07'), email: 'xs@gsuj.lk', }]; }),
- 修复:修改mockUsersService的findAll方法,直接返回预期的用户数组,无需依赖参数:
内容的提问来源于stack exchange,提问作者thi_m
相关产品推荐
相关产品推荐

