base.entity.spec.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { DeepPartial } from '@vendure/common/lib/shared-types';
  2. import { describe, expect, it } from 'vitest';
  3. import { Calculated } from '../../common/index';
  4. import { CalculatedPropertySubscriber } from '../subscribers';
  5. import { VendureEntity } from './base.entity';
  6. class ChildEntity extends VendureEntity {
  7. constructor(input?: DeepPartial<ChildEntity>) {
  8. super(input);
  9. }
  10. name: string;
  11. get nameLoud(): string {
  12. return this.name.toUpperCase();
  13. }
  14. }
  15. class ChildEntityWithCalculated extends VendureEntity {
  16. constructor(input?: DeepPartial<ChildEntity>) {
  17. super(input);
  18. }
  19. name: string;
  20. @Calculated()
  21. get nameLoudCalculated(): string {
  22. return this.name.toUpperCase();
  23. }
  24. }
  25. describe('VendureEntity', () => {
  26. it('instantiating a child entity', () => {
  27. const child = new ChildEntity({
  28. name: 'foo',
  29. });
  30. expect(child.name).toBe('foo');
  31. expect(child.nameLoud).toBe('FOO');
  32. });
  33. it('instantiating from existing entity with getter', () => {
  34. const child1 = new ChildEntity({
  35. name: 'foo',
  36. });
  37. const child2 = new ChildEntity(child1);
  38. expect(child2.name).toBe('foo');
  39. expect(child2.nameLoud).toBe('FOO');
  40. });
  41. it('instantiating from existing entity with calculated getter', () => {
  42. const calculatedPropertySubscriber = new CalculatedPropertySubscriber();
  43. const child1 = new ChildEntityWithCalculated({
  44. name: 'foo',
  45. });
  46. // This is what happens to entities after being loaded from the DB
  47. calculatedPropertySubscriber.afterLoad(child1);
  48. const child2 = new ChildEntityWithCalculated(child1);
  49. expect(child2.name).toBe('foo');
  50. expect(child2.nameLoudCalculated).toBe('FOO');
  51. });
  52. });