How to write a test that triggers an error on Insert (when using check package)?

Hi everyone,

really struggling with that one but want to aim for higher code completion and trigger the error part as well.

This is a code example:

import { check } from 'meteor/check';

import { checkStringNotEmpty } from '../../checkExtensions';

import { ICW } from '../../../collections/icw';

const insertICW = function (userId, kit1, kit2, icwObjParam) {
    // inserts an `ICW` object which is indexed via an unique compound index with `userId`, `kit1` and `kit2`
    check(userId, checkStringNotEmpty);
    check(kit1, checkStringNotEmpty);
    check(kit2, checkStringNotEmpty);
    // check quickly that the doc doesn't exist already
    if (ICW.findOne({ userId, kit1, kit2 }, { fields: { _id: 1 } })) {
        return undefined;
    }
    try {
        const icwObj = icwObjParam;
        icwObj.created = new Date();
        return ICW.insert(icwObj);
    } catch (err) {
        debugger;
        throw new Error(`Error 403 - Insert into ICW failed with error: ${err}`);
    }
};

export default insertICW;

The check() package does it’s job and has shielded us from entering all wrong data to force an error on the insert itself. Any idea how we could write the test in Mocha/Chai to trigger the catch and therefore the Error 403?

Thanks in advance!

You could stub it with sinon and force it to throw:

import { assert } from "chai";
import { stub } from "sinon";
import { ICW } from "../../../collections/icw";
describe("ICW insert", function() {
  it("Throws 403 when insert throws", function() {
    const ICWStub = stub(ICW, "insert");
    ICWStub.throws();
    try {
      assert.throws(
        () => insertICW(userId, kit1, kit2, icwObjParam),
        /Error 403 - Insert into ICW failed with error/
      );
    } finally {
      ICWStub.restore();
    }
  });
});

3 Likes

Thank you, will give it a try.

I need try once so that i can help you recognise the issue!

Sorry, your post is a bit hard to understand. The problem got solved by @coagmano excellent response already.