common.spec.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import type { HydratedDocument } from 'mongoose';
  2. import { Types } from 'mongoose';
  3. import { mock } from 'vitest-mock-extended';
  4. import { getIdForRef, isPopulated } from './common';
  5. import type { IPageHasId } from './page';
  6. import type { IPage } from './page';
  7. describe('isPopulated', () => {
  8. it('should return true when the argument implements HasObjectId', () => {
  9. // Arrange
  10. const ref = mock<IPageHasId>();
  11. // Act
  12. const result = isPopulated(ref);
  13. // Assert
  14. expect(result).toBe(true);
  15. });
  16. it('should return true when the argument is a mongoose Document', () => {
  17. // Arrange
  18. const ref = mock<HydratedDocument<IPage>>();
  19. // Act
  20. const result = isPopulated(ref);
  21. // Assert
  22. expect(result).toBe(true);
  23. });
  24. it('should return false when the argument is string', () => {
  25. // Arrange
  26. const ref = new Types.ObjectId().toString();
  27. // Act
  28. const result = isPopulated(ref);
  29. // Assert
  30. expect(result).toBe(false);
  31. });
  32. it('should return false when the argument is ObjectId', () => {
  33. // Arrange
  34. const ref = new Types.ObjectId();
  35. // Act
  36. const result = isPopulated(ref);
  37. // Assert
  38. expect(result).toBe(false);
  39. });
  40. });
  41. describe('getIdForRef', () => {
  42. it('should return the id string when the argument is populated', () => {
  43. // Arrange
  44. const id = new Types.ObjectId();
  45. const ref = mock<IPageHasId>({
  46. _id: id.toString(),
  47. });
  48. // Act
  49. const result = getIdForRef(ref);
  50. // Assert
  51. expect(result).toStrictEqual(id.toString());
  52. });
  53. it('should return the ObjectId when the argument is a mongoose Document', () => {
  54. // Arrange
  55. const id = new Types.ObjectId();
  56. const ref = mock<HydratedDocument<IPage>>({
  57. _id: id,
  58. });
  59. // Act
  60. const result = getIdForRef(ref);
  61. // Assert
  62. expect(result).toStrictEqual(id);
  63. });
  64. it('should return the id string as is when the argument is ObjectId', () => {
  65. // Arrange
  66. const ref = new Types.ObjectId();
  67. // Act
  68. const result = getIdForRef(ref);
  69. // Assert
  70. expect(result).toStrictEqual(ref);
  71. });
  72. it('should return the ObjectId as is when the argument is string', () => {
  73. // Arrange
  74. const ref = new Types.ObjectId().toString();
  75. // Act
  76. const result = getIdForRef(ref);
  77. // Assert
  78. expect(result).toStrictEqual(ref);
  79. });
  80. });