请注意,您为
我正在为一个nestjs应用程序编写一个测试,但是,输出日期和预期日期不匹配:
这是模拟生成器:
export function createMockUser(data: Partial<User>): User {
return {
id: data.id || randomUUID(),
firstName: data.firstName || faker.name.firstName(),
lastName: data.lastName || faker.name.lastName(),
emailAddress: data.emailAddress || faker.internet.email(),
createdAt: data.createdAt || new Date(),
updatedAt: data.updatedAt || new Date(),
};
}
这就是测试:
describe('create', () => {
it('creates and returns user', async () => {
const randomUser = createMockUser({});
const user = new UserEntity(randomUser);
usersServiceCreateMock.mockResolvedValue(user);
const response = await tester.http
.post('/api/users')
.set('Accept', 'application/json')
.set('Authorization', 'Bearer fake-token')
.send({
firstName: randomUser.firstName,
lastName: randomUser.lastName,
})
.expect(201);
expect(response.body).toEqual(instanceToPlain(user));
});
});
如果有人感兴趣,这就是控制器:
@UseGuards(FirebaseAuthGuard)
@ApiBearerAuth()
@UseInterceptors(ClassSerializerInterceptor)
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
async create(
@Body() createUserDto: CreateUserPostDto,
@CurUser() user: DecodedIdToken
): Promise<UserEntity> {
return await this.usersService.create({
...createUserDto,
id: user.uid,
emailAddress: user.email,
});
}
}
这是输出:
这是输出:
expect(received).toEqual(expected) // deep equality
- Expected - 3
+ Received + 3
- UserEntity {
- "createdAt": 2022-08-21T13:25:49.621Z,
+ Object {
+ "createdAt": "2022-08-21T13:25:49.771Z",
"emailAddress": "Tyshawn.Hudson@gmail.com",
"firstName": "Billy",
"id": "ead38580-287f-4003-8f8c-e1c5e2243cfd",
"lastName": "Bins",
- "updatedAt": 2022-08-21T13:25:49.621Z,
+ "updatedAt": "2022-08-21T13:25:49.772Z",
}
我不知道是什么导致了以毫秒为单位的差异。
即使我不使用instanceToPlain(user)
,结果也是一样的,如果我在日期上应用Transform,结果也是相同的,例如:
@Transform(({ value }) => value.toISOString())
createdAt: Date;
@Transform(({ value }) => value.toISOString())
updatedAt: Date;
createdAt
和updatedAt
字段创建了一个具有new Date()
的模拟用户,然后使用此用户对象在DB中创建文档。但是,正如我所设想的,createdAt
和updatedAt
时间戳并没有在您的模式中指定,而是使用全新的时间戳自动填充的。这就是为什么你会经历这些差异。