JSFiddle - React, Tailwind, and code Playground

by peterwbeck

JavaScript

import * as TypeMoq from 'typemoq';

class UnitOfWorkFactory {
  public async trans(
    work: () => Promise<void>
  ): Promise<void> {
    return await work();
  }
}

// tslint:disable-next-line:max-classes-per-file
class TestTarget {
  constructor(
    private readonly numInvocations: number,
    private readonly unitOfWorkFactory: UnitOfWorkFactory,
    private readonly service: TestService,
  ) {}

  public async doSomething(): Promise<void> {
    await this.unitOfWorkFactory.trans(async () => {
      for (let n = 0 ; n < this.numInvocations ; ++n) {
        await this.service.serviceMethod();
      }
    });
  }
}

// tslint:disable-next-line:max-classes-per-file
class TestService {
  public async serviceMethod(): Promise<void> {
    return;
  }
}

const getTestLambda = (numInvocations: number) => {
  return (async () => {
    // ARRANGE
    const unitOfWorkFactoryMock = TypeMoq.Mock.ofType<UnitOfWorkFactory>();
    unitOfWorkFactoryMock
      .setup(async (w) => w.trans(TypeMoq.It.isAny()))
      .callback(async (work: () => undefined) => {
        await work();
      });
    const serviceMock = TypeMoq.Mock.ofType<TestService>();

    // ACT
    const target = new TestTarget(
      numInvocations,
      unitOfWorkFactoryMock.object,
      serviceMock.object,
    );
    await target.doSomething();

    // ASSERT
    serviceMock.verify((m) => m.serviceMethod(), TypeMoq.Times.exactly(numInvocations));
  });
}


it('verifies service mock when invoked 1 times', getTestLambda(1));
it('verifies service mock when invoked 2 times', getTestLambda(2));
it('verifies service mock when invoked 3 times', getTestLambda(3));
it('verifies service mock when invoked 4 times', getTestLambda(4));