to-json.test.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import type { InferAttributes, InferCreationAttributes } from '@sequelize/core';
  2. import { DataTypes, Model } from '@sequelize/core';
  3. import { expect } from 'chai';
  4. import { sequelize } from '../../support';
  5. const dialect = sequelize.dialect;
  6. describe('Model#toJSON', () => {
  7. if (!dialect.supports.dataTypes.JSON) {
  8. return;
  9. }
  10. it('returns copy of json', () => {
  11. const User = sequelize.define('User', {
  12. name: DataTypes.STRING,
  13. });
  14. const user = User.build({ name: 'my-name' });
  15. const json1 = user.toJSON();
  16. expect(json1).to.deep.equal({ id: null, name: 'my-name' });
  17. // remove value from json and ensure it's not changed in the instance
  18. delete json1.name;
  19. const json2 = user.toJSON();
  20. expect(json2).to.have.property('name').and.be.equal('my-name');
  21. });
  22. it('returns clone of JSON data-types', () => {
  23. class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
  24. declare name: string;
  25. declare permissions: {
  26. admin: boolean;
  27. special: string;
  28. };
  29. }
  30. User.init(
  31. {
  32. name: DataTypes.STRING,
  33. permissions: DataTypes.JSON,
  34. },
  35. { sequelize },
  36. );
  37. const user = User.build({ name: 'my-name', permissions: { admin: true, special: 'foobar' } });
  38. const json = user.toJSON();
  39. expect(json).to.deep.equal({
  40. id: null,
  41. name: 'my-name',
  42. permissions: { admin: true, special: 'foobar' },
  43. });
  44. expect(json.permissions).not.to.equal(user.permissions);
  45. json.permissions.admin = false;
  46. expect(user.permissions.admin).to.equal(true);
  47. });
  48. });