Cannot stub non-existent property "create" of a mongoose document

Viewed 268

I'm writing unit tests for my express app using Sinon. I have a Log model:

import { Schema, model } from 'mongoose';

const LogSchema = new Schema({
    content: {
        type: String,
        required: true,
    },

    date: {
        type: Date,
        default: Date.now,
    },
});

const Log = model('Log', LogSchema);

export default Log;

And a LogController:

import Log from '../models/Log';

class LogController {
    static async create(content) {
        await Log.create({ content });
    }
}

export default LogController;

I'm trying to write tests for LogController.create().

import { createSandbox } from 'sinon';
import Log from '../../../src/models/Log';
import LogController from '../../../src/controllers/LogController';

describe('LogController', () => {
    let sandbox;
    let createStub;

    beforeEach(() => {
        sandbox = createSandbox();

        createStub = sandbox.stub(Log, 'create');
    });

    describe('create()', () => {
        it('should create a Log with the given content', async () => {
            await LogController.create('Bob Lob Law is on the house');

            expect(createStub.calledWith({ content: 'Bob Lob Law is on the house' })).to.be.true;
        });
    });

But then I get TypeError: Cannot stub non-existent property create, implying that Log doesn't have a create method. Which is weird, since I have other controllers that are tested exactly like this and they don't throw any error. I also tried stubbing it with Log.create = sandbox.stub() but I got the same error. Maybe I'm doing something wrong on my model definition? How can I fix this?

1 Answers

Sinon thinks you're trying to stub object.create for some reason (instead of model.create) possibly because model.create returns a promise, but your stub doesn't return anything. You need to change

createStub = sandbox.stub(Log, 'create');

to

createStub = sandbox.stub(Log, 'create').resolves();
Related