davesag / sequelize-test-helpers

A collection of utilities to help with unit-testing Sequelize models
https://www.npmjs.com/package/sequelize-test-helpers
MIT License
124 stars 21 forks source link

Accessing stubbed functions on Models results in "received value must be a mock or spy function" #102

Closed dieterwalckiers closed 5 years ago

dieterwalckiers commented 5 years ago

Hello

I'm integrating sequelize-test-helpers in my unit tests, but I'm having some trouble testing the stubbed functions in the Models. When I run this test:

describe("OptionCategory model", () => {
    const OptionCategory = OptionCategoryFactory(sequelize, dataTypes);
    OptionCategory.associate = ({ OptionKind }) => {
        OptionCategory.belongsTo(OptionKind);
    };
    it('defined a hasMany association with OptionCategory as "optionCategories"', () => {
        console.log("OptionCategory.belongsTo is", OptionCategory.belongsTo); // <-- this returns "spy" !
        expect(OptionCategory.belongsTo).toHaveBeenCalled();
    });
});

I get

Matcher error: received value must be a mock or spy function

    Received has type:  function
    Received has value: [Function anonymous]

Even though OptionCategory.belongsTo prints out as spy. I really don't understand why jest isn't taking it... This happens with all stubbed functions, by default or by me using sinon.

Here's a link to the test file in my (work in progress) repo, for context: https://bitbucket.org/dyte/authentic-catalog-api/src/master/tests/unit/models/optionCategory.ts

Thanks a lot for any hints! Dieter

davesag commented 5 years ago

This package is designed to work with mocha not jest but as long as you are using sinon and chai it ought to work. But I have only ever tried it with mocha. Chai/Sinon's syntax is different to Jest's. Try, at the top

const { expect } = require('chai')

and in your test

expect(OptionCategory.belongsTo).to.have.been.called
dieterwalckiers commented 5 years ago

Ok, I got rid of jest completely in favor of mocha, it works now. I'm relatively new to testing frameworks, and the similar synaxt of jest and mocha made me confuse them with each other. Thanks a lot for your help!