find-create-find.test.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. const { expect } = require('chai');
  3. const { EmptyResultError, UniqueConstraintError } = require('@sequelize/core');
  4. const { beforeAll2, sequelize } = require('../../support');
  5. const sinon = require('sinon');
  6. describe('Model#findCreateFind', () => {
  7. const vars = beforeAll2(() => {
  8. const TestModel = sequelize.define('TestModel', {});
  9. return { TestModel };
  10. });
  11. beforeEach(function () {
  12. this.sinon = sinon.createSandbox();
  13. });
  14. afterEach(function () {
  15. this.sinon.restore();
  16. });
  17. it('should return the result of the first find call if not empty', async function () {
  18. const { TestModel } = vars;
  19. const result = {};
  20. const where = { prop: Math.random().toString() };
  21. const findSpy = this.sinon.stub(TestModel, 'findOne').resolves(result);
  22. await expect(
  23. TestModel.findCreateFind({
  24. where,
  25. }),
  26. ).to.eventually.eql([result, false]);
  27. expect(findSpy).to.have.been.calledOnce;
  28. expect(findSpy.getCall(0).args[0].where).to.equal(where);
  29. });
  30. it('should create if first find call is empty', async function () {
  31. const { TestModel } = vars;
  32. const result = {};
  33. const where = { prop: Math.random().toString() };
  34. const createSpy = this.sinon.stub(TestModel, 'create').resolves(result);
  35. this.sinon.stub(TestModel, 'findOne').resolves(null);
  36. await expect(
  37. TestModel.findCreateFind({
  38. where,
  39. }),
  40. ).to.eventually.eql([result, true]);
  41. expect(createSpy).to.have.been.calledWith(where);
  42. });
  43. for (const Error of [EmptyResultError, UniqueConstraintError]) {
  44. it(`should do a second find if create failed due to an error of type ${Error.name}`, async function () {
  45. const { TestModel } = vars;
  46. const result = {};
  47. const where = { prop: Math.random().toString() };
  48. const findSpy = this.sinon.stub(TestModel, 'findOne');
  49. this.sinon.stub(TestModel, 'create').rejects(new Error());
  50. findSpy.onFirstCall().resolves(null);
  51. findSpy.onSecondCall().resolves(result);
  52. await expect(
  53. TestModel.findCreateFind({
  54. where,
  55. }),
  56. ).to.eventually.eql([result, false]);
  57. expect(findSpy).to.have.been.calledTwice;
  58. expect(findSpy.getCall(1).args[0].where).to.equal(where);
  59. });
  60. }
  61. });