Reputation: 537
I am writing unit test. I need to mock ObjectId. How can I do this?
const mockTokenDto: CreateUserTokenDto = {
token:
'a172c98424ad6c6269d398de476940e29feacea5f8ab270ecbc45262ec1d6f04a4abd223925bb0759e915f96c7aaf196',
userId: '5fa1c587ae2ac23e9c46510f',
expireAt: '2020-11-04T21:06:26.236Z',
}
export class CreateUserTokenDto {
@IsString()
token: string;
@IsString()
userId: mongoose.Types.ObjectId;
@IsDateString()
expireAt: string;
}
Upvotes: 0
Views: 5331
Reputation: 31
Found another way to mock ObjectId generation. Just mock ObjectID.generate. For example, mock with constant:
const { BSON } = require('bson');
jest.spyOn(BSON.ObjectID.prototype, 'generate').mockImplementation(() => {
return Buffer.from('62a23958e5a9e9b88f853a67', 'hex');
});
Mock implementation can be replaced with chained 'mockImplementationOnce', if more than one id need to be generated
Upvotes: 3
Reputation: 1634
The accepted answer is not a mock.. it is a real ObjectId
If you came here looking to solve the problem of ever changing ObjectIds in your snapshots / tests then look no furhter.
Unfortunately mocking mongoose.Types.ObjectId
is not easy, if you try to spyOn
or jest.fn()
the exported type from mongoose
you will get errors relating to primitive types.
Here is the solution:
mongoose.Types.ObjectId
This makes it easy to re-use the type across your codebase anyway,
import mongoose from 'mongoose';
export type ObjectId = mongoose.Types.ObjectId;
export const ObjectId = mongoose.Types.ObjectId;
https://jestjs.io/docs/configuration#setupfiles-array
import * as ObjectIdWrapper from '../../src/shared/classes/object-id';
const mockId = new ObjectIdWrapper.ObjectId('62a23958e5a9e9b88f853a67');
const ObjectIdSpy = jest.spyOn(ObjectIdWrapper, 'ObjectId');
ObjectIdSpy.mockImplementation(() => mockId);
Upvotes: 2
Reputation: 1318
You can create a mock ObjectId using mongoose.Types.ObjectId
const mockObjectId = new mongoose.Types.ObjectId();
const mockTokenDto: CreateUserTokenDto = {
token:
'a172c98424ad6c6269d398de476940e29feacea5f8ab270ecbc45262ec1d6f04a4abd223925bb0759e915f96c7aaf196',
userId: mockObjectId,
expireAt: '2020-11-04T21:06:26.236Z',
}
You can learn more about it here https://mongoosejs.com/docs/api/mongoose.html#types-objectid-js
Upvotes: 0