Skip to content
Snippets Groups Projects
mailer.service.spec.ts 4.77 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { HttpModule, HttpService } from '@nestjs/axios';
    
    import { Test } from '@nestjs/testing';
    
    import { AxiosResponse } from 'axios';
    import * as fs from 'fs';
    import * as path from 'path';
    
    import { of, throwError } from 'rxjs';
    import { ConfigurationService } from '../configuration/configuration.service';
    import { MailerService } from './mailer.service';
    
    
    describe('MailerService', () => {
    
      let mailerService: MailerService;
    
      const httpServiceMock = {
        get: jest.fn(),
        post: jest.fn(),
      };
    
    
      beforeEach(async () => {
    
        const module = await Test.createTestingModule({
    
          providers: [
            MailerService,
            ConfigurationService,
            {
              provide: HttpService,
              useValue: httpServiceMock,
            },
          ],
    
        mailerService = module.get<MailerService>(MailerService);
    
      });
    
      it('should be defined', () => {
    
        expect(mailerService).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: {},
          };
    
          httpServiceMock.post.mockImplementationOnce(() => of(result));
    
          expect(await mailerService.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: {},
          };
    
          httpServiceMock.post.mockImplementationOnce(() => throwError(result));
    
          try {
    
            await mailerService.send('a@a.com', 'test', '<p>This is a test</p>');
    
            expect(true).toBe(false);
    
          } 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(mailerService.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(mailerService.getTemplateLocation(filename)).toBe('/path/to/template');
    
            expect(true).toBe(false);
    
          } 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(mailerService.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(mailerService.loadJsonConfig(filename)).toBe('/path/to/template');
    
            expect(true).toBe(false);
    
          } 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(mailerService.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.<br/><br/>Pour nous contacter : <a href="mailto:inclusionnumerique@grandlyon.com">inclusionnumerique@grandlyon.com</a></p>`