mockingoose
mockingoose copied to clipboard
Mockingoose with typescript
Hi. As in the title im trying to implement mockingoose with typescript however i keep getting error "TypeError: Cannot read properties of null (reading 'Decimal128')". Already jumped through some hoops but cant figure out that one. My code
model
import { Schema, model } from 'mongoose';
import { Schemas } from './schemas';
import Ajv from 'ajv';
import ajvAddFormats from 'ajv-formats';
const ajv = new Ajv({
unicodeRegExp: false,
strict: false,
});
ajvAddFormats(ajv);
const schemas = new Schemas();
const userSchema = schemas.getUserSchema();
const User = new Schema({}, { strict: false });
User.pre('validate', function (next) {
const validate = ajv.compile(userSchema);
const schemaValidation = validate(this);
if (!schemaValidation) console.error(validate.errors);
next();
});
User.pre('save', function (next) {
this.timestamp = Date.now();
next();
});
// QED: a
export const User = model('User', User);
controller
export const createUser = async (
data: any
): Promise<object> => {
const evidence = claimData.verification?.evidence;
console.log(uprn, claimData);
const user = new User({
name: data.name,
surname: data.surname
});
console.log(user);
await user.save((err: Error) => {
if (err) {
logger.error(err);
throw new InternalServerError();
}
});
return { _id: user._id };
};
// test.ts file
import * as User from '../../src/controllers/user;
import * as schema from '../../src/models/VerifiedClaim';
// here i had some type errors if i didnt do that
// @ts-ignore
import * as mockingoose from 'mockingoose';
describe('createUser', () => {
spyConsole();
beforeEach(() => {
jest.resetModules();
jest.clearAllMocks();
});
it('should return _id of newly created object upon creation', async () => {
mockingoose(User).toReturn({ _id: 'id999' }, 'save');
const response = await User.createUser({
name: 'James',
surname: 'Brown',
});
expect(response).toEqual({ _id: 'id999' });
});
});
We are using ajv schema validation instead of regular mongoose schema and it shouldnt affect it, but thought you better know. Any idea why that error might be happening. Thank you very much for any suggestions.
EDIT: Ah, check the supported version. Guess you are not going to support mongoose 6 any time soon? EDIT2: Ok it turn out its not mocking the constructor i think. Prticularly in case of "new User". So far it seems to be working with everything else.
Could you share working example ?