expect(received).toEqual(expected)//深度相等错误Jest单元测试

nlejzf6q  于 2023-01-10  发布在  Jest
关注(0)|答案(1)|浏览(250)

我正在用Jest做单元测试,在user. controller. spec. ts文件中得到了错误。其他文件都通过了。
旧错误
'通过源/应用程序控制器规范ts(10.482秒)通过源/用户/服务/用户服务规范ts(11.629秒)失败源/用户/控制器/用户控制器规范ts(12.239秒)●用户控制器›应创建一个用户

expect(received).toEqual(expected) // deep equality

- Expected  - 5
+ Received  + 1

- Object {
-   "birthDate": 2000-06-07T00:00:00.000Z,
-   "email": "xs@gsuj.lk",
-   "name": "aqs",
- }
+ Promise {}

  45 |   it('should create a user' , () =>{
  46 |     const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : "xs@gsuj.lk" };
> 47 |     expect(controller.create(dto)).toEqual({
     |                                    ^
  48 |
  49 |       name:dto.name,
  50 |       birthDate :dto.birthDate,

  at Object.<anonymous> (src/users/controllers/users.controller.spec.ts:47:36)

旧错误已解决,现在出现此新错误。

PASS  src/app.controller.spec.ts (10.573 s)

通过src/用户/服务/用户服务规范ts(11.867秒)失败src/用户/控制器/用户控制器规范ts(12.282秒)●用户控制器›应创建

expect(received).toEqual(expected) // deep equality

Expected: {"birthDate": 2000-06-07T00:00:00.000Z, "email": "xs@gsuj.lk", "id": 2, "name": "aqs"}
Received: "user created successfully"

  62 |     const data = await controller.create(dto);
  63 |
> 64 |          expect(data).toEqual({
     |                       ^
  65 |           id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : "xs@gsuj.lk"
  66 |          })
  67 |     expect(controller).toBeDefined();

  at src/users/controllers/users.controller.spec.ts:64:23
  at fulfilled (src/users/controllers/users.controller.spec.ts:5:58)

测试套件:2次未通过,2次通过,共4次测试:1例未通过,4例通过,共5例
这是较旧的用户.控制器.规范. ts文件

`import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '../services/users.service';
import { UsersController } from './users.controller';

describe('UsersController', () => {
  let controller: UsersController; 
  
   const mockUsersService ={
    create: jest.fn(dto => {
      return {
         
        ...dto
      };
    }),
    update:jest.fn((id,dto) =>({
      id,
      ...dto
    }))
   }

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers:[UsersService],
    })
    .overrideProvider(UsersService)
    .useValue(mockUsersService)
    .compile();

    //get service module from user module
     controller = module.get<UsersController>(UsersController);
  });

  //check if service available
  it('should be defined', () => {
    expect(controller).toBeDefined();
  });

  // it('hould create a user', () => {
  //   expect(controller.create({name:'aqs'})).toEqual({

  //   });
  // });

  it('should create a user' , () =>{
    const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : "xs@gsuj.lk" };
    expect(controller.create(dto)).toEqual({
      id:dto.id,
      name:dto.name,
      birthDate :dto.birthDate,
      email : dto.email
    });

    expect(mockUsersService.create).toHaveBeenCalledWith(dto);
  });
})

这是新的用户.控制器.规范. ts文件

> import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from '../services/users.service';
import { UsersController } from './users.controller';

describe('UsersController', () => {
  let controller: UsersController; 
  
   const mockUsersService ={
    create: jest.fn(dto => {
      return {
         
        ...dto
      };
    }),
    update:jest.fn((id,dto) =>({
      id,
      ...dto
    }))
   }

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers:[UsersService],
    })
    .overrideProvider(UsersService)
    .useValue(mockUsersService)
    .compile();

    //get service module from user module
     controller = module.get<UsersController>(UsersController);
  });

  //check if service available
  it('should be defined', () => {
    expect(controller).toBeDefined();
  });

  // it('hould create a user', () => {
  //   expect(controller.create({name:'aqs'})).toEqual({

  //   });
  // });

  // it('should create a user' , () =>{
  //   const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : "xs@gsuj.lk" };

  //   expect(controller.create(dto)).toEqual({
  //     id:dto.id,
  //     name:dto.name,
  //     birthDate :dto.birthDate,
  //     email : dto.email
  //   });
    
  //   expect(mockUsersService.create).toHaveBeenCalledWith(dto);
  // });

  it('should create', async () => {

    const dto ={id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : "xs@gsuj.lk" };

    const data = await controller.create(dto);
     
         expect(data).toEqual({ 
          id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : "xs@gsuj.lk" 
         })
    expect(controller).toBeDefined();
  });

   
})

用户服务规范ts文件

import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { getRepository } from 'typeorm';
//import { UsersController } from '../controllers/users.controller';
import { UsersService } from './users.service';
import {User} from '../entities/user.entity'

describe('UsersService', () => {
  let service: UsersService;
//  let providers:UsersController;

const mockUsersRepository ={
  create:jest.fn().mockImplementation(dto =>dto),
  save:jest.fn().mockImplementation(user => Promise.resolve({id:2, ...user}))

}

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UsersService, {
        provide:getRepositoryToken(User),
        useValue:mockUsersRepository,
      },
    ],
    }).compile();

    service = module.get<UsersService>(UsersService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  it('should be create a new user record and return that', async () => {
    expect( await service.create({id:2, name:'aqs',birthDate: new Date('2000-06-07'), email : "xs@gsuj.lk" })).toEqual({
      id:2, 
      name:'aqs',
      birthDate: new Date('2000-06-07'), 
      email : "xs@gsuj.lk" ,
    });
  });

});

`
bmvo0sr5

bmvo0sr51#

您的controller.create()返回了一个非预期的承诺您应该等待控制器数据,如下所示:

const data = await controller.create(whatever);
expect(data).toEqual(expectedData)

相关问题