Jest.js 无法通过toBeInstanceOf测试

xurqigkl  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(220)

我正在做一个TTD项目,使用NestJs和Jest。直到现在一切都很好,我不知道如何通过我的toBeInstanceOf测试。返回的对象应该是User类型,但是Jest告诉我:

expect(received).toBeInstanceOf(expected)

Expected constructor: User
Received constructor: Object

下面是测试:

import { IRepository } from '../../../core/src/domain/repositories/IRepository.interface';
import { User } from '../../src/domain/entities/user.entity';
import { CreateUserUseCase } from '../../src/useCases/createUser.usecase';

const fakeUser: User = {
  id: 1,
  uuid: 'some-uuid',
  createdAt: new Date(),
  updatedAt: new Date(),
  email: '',
  password: '',
};

const userToCreate = new User();
userToCreate.email = 'test@gmail.com';
userToCreate.password = 'test';

describe('CreateUserUseCase', () => {
  let useCase: CreateUserUseCase;
  let repository: IRepository<User>;

  beforeEach(async () => {
    repository = {
      insert: jest.fn((entity: User) => {
        const newUser: User = {
          ...fakeUser,
          email: entity.email,
          password: entity.password,
        };

        return Promise.resolve(newUser);
      }),
    } as IRepository<User>;

    useCase = new CreateUserUseCase(repository);
  });

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

  describe('execute', () => {
    it('should creates a new user', async () => {
      const createdUser: User = await useCase.execute(userToCreate);

      expect(createdUser).toBeInstanceOf(User);
      expect(createdUser).toEqual({
        ...fakeUser,
        email: userToCreate.email,
        password: userToCreate.password,
      });

      expect(repository.insert).toBeCalledTimes(1);
      expect(repository.insert).toBeCalledWith({
        email: userToCreate.email,
        password: userToCreate.password,
      });
    });
  });
});

创建用户.usecase.ts

import { IRepository } from '../../../core/src/domain/repositories/IRepository.interface';
import { User } from '../domain/entities/user.entity';

export class CreateUserUseCase {
  constructor(private readonly _repository: IRepository<User>) {}

  async execute(userToCreate: User): Promise<User> {
    const createdUser: User = await this._repository.insert(userToCreate);
    return createdUser;
  }
}

I系统信息库

import { BaseEntity } from '../entities/base.entity';

export interface IRepository<T extends BaseEntity> {
  insert(entity: T): Promise<T>;
}

你知道吗?
谢谢你!

ru9i0ody

ru9i0ody1#

你的insert mock返回一个 * 看起来 * 像User的对象,但它不是类本身的示例,所以toBeInstanceOf()失败。

class Foo {
  foo: string
}

expect({  foo: 'Hello World!' }).toBeInstanceOf(Foo);

即使该对象满足Foo的结构,您也会认为这会失败,因为它是一个常规对象,而不是一个实际的示例。
更改您的insert mock以返回类的示例,您的测试应该会自行解析。

相关问题