Skip to content
Snippets Groups Projects
mailer.service.spec.ts 4.45 KiB
Newer Older
import { HttpModule, HttpService } from '@nestjs/axios';
import { Test, TestingModule } from '@nestjs/testing';
import { of, throwError } from 'rxjs';
import { AxiosResponse } from 'axios';
import { ConfigurationService } from '../configuration/configuration.service';
import { MailerService } from './mailer.service';
import * as fs from 'fs';
import * as path from 'path';

describe('MailerService', () => {
  let service: MailerService;
  let httpService: HttpService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [HttpModule],
      providers: [MailerService, ConfigurationService],
    }).compile();

    service = module.get<MailerService>(MailerService);
    httpService = module.get<HttpService>(HttpService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('email sending', () => {
    it('should send email', async () => {
      const result: AxiosResponse = {
        data: {
          status: 200,
          content: {
            success: true,
            response: [7010],
          },
        },
        status: 200,
        statusText: 'OK',
        headers: {},
        config: {},
      };
      jest.spyOn(httpService, 'post').mockImplementationOnce(() => of(result));
      expect(await service.send('a@a.com', 'test', '<p>This is a test</p>')).toBe(result.data);
    });

    it('should not send email', async () => {
      const result: AxiosResponse = {
        data: {
          errors: ['Subject cannot be blank'],
          detail: 'There was a validation error',
          status: 400,
          type: 'validation_error',
          title: 'There was a validation error',
        },
        status: 400,
        statusText: 'KO',
        headers: {},
        config: {},
      };
      jest.spyOn(httpService, 'post').mockImplementationOnce(() => throwError(result));
      try {
        await service.send('a@a.com', 'test', '<p>This is a test</p>');
      } catch (e) {
        expect(e.data.detail).toBe('There was a validation error');
        expect(e.status).toBe(400);
      }
    });
  describe('template location', () => {
    it('should get template location', async () => {
      jest.spyOn(path, 'join').mockImplementationOnce(() => '/path/to/template');
      jest.spyOn(fs, 'existsSync').mockImplementationOnce(() => true);
      expect(service.getTemplateLocation('filename')).toBe('/path/to/template');
    });

    it('should not get template location', async () => {
      const filename = 'templateFile';
      jest.spyOn(path, 'join').mockImplementationOnce(() => '/path/to/filename');
      jest.spyOn(fs, 'existsSync').mockImplementationOnce(() => false);
      try {
        expect(service.getTemplateLocation(filename)).toBe('/path/to/template');
      } catch (e) {
        expect(e.message).toBe(`Email template '${filename}' cannot be found in ./src/mailer/mail-templates`);
      }
    });
  describe('json config', () => {
    it('should get template location', async () => {
      jest.spyOn(path, 'join').mockImplementationOnce(() => '/path/to/template');
      jest.spyOn(fs, 'existsSync').mockImplementationOnce(() => true);
      const data = { test: 'test value', value: 'this is the value' };
      const buf = Buffer.from(JSON.stringify(data), 'utf8');
      jest.spyOn(fs, 'readFileSync').mockImplementationOnce(() => buf);
      jest.spyOn(JSON, 'parse').mockImplementationOnce(() => JSON.stringify(data));
      expect(service.loadJsonConfig('filename')).toStrictEqual(JSON.stringify(data));
    });

    it('should not get template location', async () => {
      const filename = 'templateFile';
      jest.spyOn(path, 'join').mockImplementationOnce(() => '/path/to/filename');
      jest.spyOn(fs, 'existsSync').mockImplementationOnce(() => false);
      try {
        expect(service.loadJsonConfig(filename)).toBe('/path/to/template');
      } catch (e) {
        expect(e.message).toBe(
          `Email json definition file '${filename}' cannot be found in ./src/mailer/mail-templates`
        );
      }
    });
  });

  it('should add signature', async () => {
    const test = '<p>test email</p>';
    expect(service.addSignature(test)).toBe(
      `<p>test email</p><br /><br /><p>L’équipe projet inclusion numérique.</p><p style="font-family:helvetica;font-size:24px;font-weight:bold;margin:0;">rés<span style="color:red;font-weight:400;">’in</span></p><br /><br /><p>Ce mail est automatique. Merci de ne pas y répondre.</p>`