BlinkUX / sequelize-mock

A simple mock interface specifically for testing code relying on Sequelize models
https://sequelize-mock.readthedocs.io
MIT License
138 stars 73 forks source link

count() method missing on Model #64

Open grimurd opened 5 years ago

grimurd commented 5 years ago

I'm using the count() method on a few of my models but it seems to be missing from the sequelize-mock API

See: http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-count

salauddinn commented 4 years ago

any update on this?

farbodsalimi commented 3 years ago

If you're using jest:

let mockModel;
jest.doMock("path/to/model", () => {
  mockModel = dbConnectionMock.define("MyModel", myMockModel);

  mockModel.count = () => 1;

  return mockModel;
});
JacopoMadaluni commented 3 years ago

We are currently using sinon and we have the same problems as sinon does not allow to stub non-existent properties by design. Does anyone know if Sequelize is planning to fix this in a timely manner ? Btw same problem applies to other non-existing methods such as findByPk() which causes the same problem of count()

LiamKarlMitchell commented 9 months ago

So findAndCount does exist.

mockModel.count = () => mockModel.findAndCount().then(res => res.count);

But this feels like something that should be added in.

Could model.js be extended?

/**
 * Executes a mock query to find instances with any provided options and return the count.
 * Without any other configuration, the default behavior when no queueud query result 
 * is present is to return single result based on the where query in the options and
 * wraps it in a promise.
 * 
 * To turn off this behavior, the `$autoQueryFallback` option on the model should be set
 * to `false`.
 * 
 * @example
 * // This is an example of the default behavior with no queued results
 * // If there is a queued result or failure, that will be returned instead
 * User.count({
 *  where: {
 *      email: 'myEmail@example.com',
 *  },
 * }).then(function (count) {
 *    // count is an integer of how many rows were found.
 * });
 * 
 * @instance
 * @method count
 * @param {Object} [options] Options for the count query
 * @param {Object} [options.where] Values that any automatically created Instances should have
 * @return {Promise<Object>} result returned by the mock query
 **/
fakeModel.prototype.count =  function (options) {
    var self = this;

    return this.$query({
        query: "count",
        queryOptions: arguments,
        fallbackFn: !this.options.autoQueryFallback ? null : function () {
            return Promise.resolve([ self.build(options ? options.where : {}) ])
                .then(function(result){
                    return Promise.resolve(result.length);
                });
        },
    });
};