Typescript Jest Unit Test Example

Date: 2019-09-11
// AttentionDayService.spec.ts
import { AttentionDayService } from "./AttentionDayService";
import { TestWiring } from "../../wiring/TestWiring";
import { IAttentionDayRepository } from "../ports/secondary/IAttentionDayRepository";
import { IAttentionDay, KindOfAttentionDay } from "../models/IAttentionDay";
import { ValidationError } from "../models/ErrorTypes/ValidationError";

describe("AttentionDayService", () => {
    let attentionDayRepository: IAttentionDayRepository;
    let attentionDayService: AttentionDayService;

    beforeAll(() => {
        const wiring = new TestWiring();
        const resolver = wiring.portResolver;
        attentionDayRepository = {} as IAttentionDayRepository;
        resolver.registerInstance("IAttentionDayRepository", () => attentionDayRepository);
        attentionDayService = new AttentionDayService()
    });

    it("should call getById() from requestById()", async () => {
        const attentionDay = {} as IAttentionDay;
        attentionDayRepository.getById = jest.fn(_ => Promise.resolve(attentionDay));
        const result = attentionDayService.requestById("abc");
        expect(attentionDayRepository.getById).toHaveBeenCalledTimes(1);
        expect(attentionDayRepository.getById).toHaveBeenCalledWith("abc");
        await expect(result).resolves.toBe(attentionDay);
    })

    it("should call updateAttentionDay() from requestUpdateAttentionDay()", async () => {
        const attentionDay = {
            id: 12,
            name: "Fake",
            start: new Date(2011, 1, 1),
            end: new Date(2011, 1, 1),
            kind: KindOfAttentionDay.AttentionDay
        } as IAttentionDay;
        attentionDayRepository.updateAttentionDay = jest.fn(_ => Promise.resolve(attentionDay));
        const result = attentionDayService.requestUpdateAttentionDay(attentionDay);
        expect(attentionDayRepository.updateAttentionDay).toHaveBeenCalledTimes(1);
        expect(attentionDayRepository.updateAttentionDay).toHaveBeenCalledWith(attentionDay);
        await expect(result).resolves.toBe(attentionDay);
    })

    it("should call updateAttentionDay() from requestUpdateAttentionDay()", async () => {
        const attentionDay = {
            id: 12,
            name: "InvalidAttentionDay",
            start: new Date(2011, 2, 1),
            end: new Date(2011, 1, 1),
            kind: KindOfAttentionDay.AttentionDay
        } as IAttentionDay;
        attentionDayRepository.updateAttentionDay = jest.fn(_ => Promise.resolve(attentionDay));
        await expect(attentionDayService.requestUpdateAttentionDay(attentionDay)).rejects.toThrow(ValidationError);
        expect(attentionDayRepository.updateAttentionDay).toHaveBeenCalledTimes(0);
    })
});

export {};
25700cookie-checkTypescript Jest Unit Test Example