upsert.test.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. 'use strict';
  2. const chai = require('chai');
  3. const expect = chai.expect;
  4. const Support = require('../../support');
  5. const current = Support.sequelize;
  6. const sinon = require('sinon');
  7. const { DataTypes, Sequelize } = require('@sequelize/core');
  8. describe(Support.getTestDialectTeaser('Model'), () => {
  9. if (current.dialect.supports.upserts) {
  10. describe('method upsert', () => {
  11. before(function () {
  12. this.User = current.define('User', {
  13. name: DataTypes.STRING,
  14. virtualValue: {
  15. type: DataTypes.VIRTUAL,
  16. set(val) {
  17. this.value = val;
  18. },
  19. get() {
  20. return this.value;
  21. },
  22. },
  23. value: DataTypes.STRING,
  24. secretValue: {
  25. type: DataTypes.INTEGER,
  26. allowNull: false,
  27. },
  28. createdAt: {
  29. type: DataTypes.DATE,
  30. field: 'created_at',
  31. },
  32. });
  33. this.UserNoTime = current.define(
  34. 'UserNoTime',
  35. {
  36. name: DataTypes.STRING,
  37. },
  38. {
  39. timestamps: false,
  40. },
  41. );
  42. });
  43. beforeEach(function () {
  44. this.query = sinon.stub(current, 'queryRaw').resolves();
  45. this.stub = sinon
  46. .stub(current.queryInterface, 'upsert')
  47. .resolves([this.User.build(), true]);
  48. });
  49. afterEach(function () {
  50. this.query.restore();
  51. this.stub.restore();
  52. });
  53. it('skip validations for missing fields', async function () {
  54. await expect(
  55. this.User.upsert({
  56. name: 'Grumpy Cat',
  57. }),
  58. ).not.to.be.rejectedWith(Sequelize.ValidationError);
  59. });
  60. it('creates new record with correct field names', async function () {
  61. await this.User.upsert({
  62. name: 'Young Cat',
  63. virtualValue: '999',
  64. });
  65. expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
  66. 'name',
  67. 'value',
  68. 'created_at',
  69. 'updatedAt',
  70. ]);
  71. });
  72. it('creates new record with timestamps disabled', async function () {
  73. await this.UserNoTime.upsert({
  74. name: 'Young Cat',
  75. });
  76. expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal(['name']);
  77. });
  78. it('updates all changed fields by default', async function () {
  79. await this.User.upsert({
  80. name: 'Old Cat',
  81. virtualValue: '111',
  82. });
  83. expect(Object.keys(this.stub.getCall(0).args[2])).to.deep.equal([
  84. 'name',
  85. 'value',
  86. 'updatedAt',
  87. ]);
  88. });
  89. });
  90. }
  91. });