common.spec.ts 2.3 KB

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