count.test.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. const chai = require('chai');
  3. const expect = chai.expect;
  4. const Support = require('../support');
  5. const { DataTypes } = require('@sequelize/core');
  6. describe(Support.getTestDialectTeaser('Hooks'), () => {
  7. beforeEach(async function () {
  8. this.User = this.sequelize.define('User', {
  9. username: {
  10. type: DataTypes.STRING,
  11. allowNull: false,
  12. },
  13. mood: {
  14. type: DataTypes.ENUM(['happy', 'sad', 'neutral']),
  15. },
  16. });
  17. await this.sequelize.sync({ force: true });
  18. });
  19. describe('#count', () => {
  20. beforeEach(async function () {
  21. await this.User.bulkCreate([
  22. { username: 'adam', mood: 'happy' },
  23. { username: 'joe', mood: 'sad' },
  24. { username: 'joe', mood: 'happy' },
  25. ]);
  26. });
  27. describe('on success', () => {
  28. it('hook runs', async function () {
  29. let beforeHook = false;
  30. this.User.beforeCount(() => {
  31. beforeHook = true;
  32. });
  33. const count = await this.User.count();
  34. expect(count).to.equal(3);
  35. expect(beforeHook).to.be.true;
  36. });
  37. it('beforeCount hook can change options', async function () {
  38. this.User.beforeCount(options => {
  39. options.where.username = 'adam';
  40. });
  41. await expect(this.User.count({ where: { username: 'joe' } })).to.eventually.equal(1);
  42. });
  43. });
  44. describe('on error', () => {
  45. it('in beforeCount hook returns error', async function () {
  46. this.User.beforeCount(() => {
  47. throw new Error('Oops!');
  48. });
  49. await expect(this.User.count({ where: { username: 'adam' } })).to.be.rejectedWith('Oops!');
  50. });
  51. });
  52. });
  53. });