find-by-pk.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { DataTypes, Model } from '@sequelize/core';
  2. import { getTestDialectTeaser, sequelize } from '../../support';
  3. import { expect } from 'chai';
  4. import sinon from 'sinon';
  5. describe(getTestDialectTeaser('Model'), () => {
  6. describe('findByPk', () => {
  7. beforeEach(() => {
  8. sinon.stub(Model, 'findAll').resolves();
  9. });
  10. afterEach(() => {
  11. sinon.restore();
  12. });
  13. it('should call internal findOne() method if findOne() is overridden', async () => {
  14. const testModel = sequelize.define('model', {
  15. unique1: {
  16. type: DataTypes.INTEGER,
  17. unique: 'unique',
  18. },
  19. unique2: {
  20. type: DataTypes.INTEGER,
  21. unique: 'unique',
  22. },
  23. });
  24. testModel.findOne = sinon.stub();
  25. sinon.spy(Model, 'findOne');
  26. await testModel.findByPk(1);
  27. testModel.findOne.should.not.have.been.called;
  28. Model.findOne.should.have.been.called;
  29. });
  30. it('should use composite primary key when querying table has one', async () => {
  31. const testModel = sequelize.define('model', {
  32. pk1: {
  33. type: DataTypes.INTEGER,
  34. primaryKey: true,
  35. },
  36. pk2: {
  37. type: DataTypes.INTEGER,
  38. primaryKey: true,
  39. },
  40. });
  41. const findOneSpy = sinon.spy(Model, 'findOne');
  42. await testModel.findByPk({ pk1: 1, pk2: 2 });
  43. findOneSpy.should.have.been.calledWithMatch({
  44. where: { pk1: 1, pk2: 2 },
  45. });
  46. });
  47. it('should throw error if composite primary key args not match key', async () => {
  48. const testModel = sequelize.define('model', {
  49. pk1: {
  50. type: DataTypes.INTEGER,
  51. primaryKey: true,
  52. },
  53. pk2: {
  54. type: DataTypes.INTEGER,
  55. primaryKey: true,
  56. },
  57. });
  58. await expect(testModel.findByPk({ pk1: 1 })).to.eventually.be.rejectedWith(TypeError);
  59. });
  60. it('should throw error if wrong type passed and model has composite primary key', async () => {
  61. const testModel = sequelize.define('model', {
  62. pk1: {
  63. type: DataTypes.INTEGER,
  64. primaryKey: true,
  65. },
  66. pk2: {
  67. type: DataTypes.INTEGER,
  68. primaryKey: true,
  69. },
  70. });
  71. await expect(testModel.findByPk(1)).to.eventually.be.rejectedWith(TypeError);
  72. });
  73. });
  74. });