restore.test.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. const sinon = require('sinon');
  7. describe(Support.getTestDialectTeaser('Hooks'), () => {
  8. beforeEach(async function () {
  9. this.User = this.sequelize.define('User', {
  10. username: {
  11. type: DataTypes.STRING,
  12. allowNull: false,
  13. },
  14. mood: {
  15. type: DataTypes.ENUM(['happy', 'sad', 'neutral']),
  16. },
  17. });
  18. this.ParanoidUser = this.sequelize.define(
  19. 'ParanoidUser',
  20. {
  21. username: DataTypes.STRING,
  22. mood: {
  23. type: DataTypes.ENUM(['happy', 'sad', 'neutral']),
  24. },
  25. },
  26. {
  27. paranoid: true,
  28. },
  29. );
  30. await this.sequelize.sync({ force: true });
  31. });
  32. describe('#restore', () => {
  33. describe('on success', () => {
  34. it('should run hooks', async function () {
  35. const beforeHook = sinon.spy();
  36. const afterHook = sinon.spy();
  37. this.ParanoidUser.beforeRestore(beforeHook);
  38. this.ParanoidUser.afterRestore(afterHook);
  39. const user = await this.ParanoidUser.create({ username: 'Toni', mood: 'happy' });
  40. await user.destroy();
  41. await user.restore();
  42. expect(beforeHook).to.have.been.calledOnce;
  43. expect(afterHook).to.have.been.calledOnce;
  44. });
  45. });
  46. describe('on error', () => {
  47. it('should return an error from before', async function () {
  48. const beforeHook = sinon.spy();
  49. const afterHook = sinon.spy();
  50. this.ParanoidUser.beforeRestore(() => {
  51. beforeHook();
  52. throw new Error('Whoops!');
  53. });
  54. this.ParanoidUser.afterRestore(afterHook);
  55. const user = await this.ParanoidUser.create({ username: 'Toni', mood: 'happy' });
  56. await user.destroy();
  57. await expect(user.restore()).to.be.rejected;
  58. expect(beforeHook).to.have.been.calledOnce;
  59. expect(afterHook).not.to.have.been.called;
  60. });
  61. it('should return an error from after', async function () {
  62. const beforeHook = sinon.spy();
  63. const afterHook = sinon.spy();
  64. this.ParanoidUser.beforeRestore(beforeHook);
  65. this.ParanoidUser.afterRestore(() => {
  66. afterHook();
  67. throw new Error('Whoops!');
  68. });
  69. const user = await this.ParanoidUser.create({ username: 'Toni', mood: 'happy' });
  70. await user.destroy();
  71. await expect(user.restore()).to.be.rejected;
  72. expect(beforeHook).to.have.been.calledOnce;
  73. expect(afterHook).to.have.been.calledOnce;
  74. });
  75. });
  76. });
  77. });