1+ import { Test , TestingModule } from '@nestjs/testing' ;
2+ import { EmailTemplateService } from './email-template.service' ;
3+ import { InternalServerErrorException } from '@nestjs/common' ;
4+ import * as fs from 'fs' ;
5+ import * as path from 'path' ;
6+
7+ // Mock the fs module so we don't hit the real disk
8+ jest . mock ( 'fs' ) ;
9+
10+ describe ( 'EmailTemplateService' , ( ) => {
11+ let service : EmailTemplateService ;
12+
13+ beforeEach ( async ( ) => {
14+ const module : TestingModule = await Test . createTestingModule ( {
15+ providers : [ EmailTemplateService ] ,
16+ } ) . compile ( ) ;
17+
18+ service = module . get < EmailTemplateService > ( EmailTemplateService ) ;
19+ } ) ;
20+
21+ afterEach ( ( ) => {
22+ jest . clearAllMocks ( ) ;
23+ jest . restoreAllMocks ( ) ;
24+ } ) ;
25+
26+ it ( 'should be defined' , ( ) => {
27+ expect ( service ) . toBeDefined ( ) ;
28+ } ) ;
29+
30+ describe ( 'render' , ( ) => {
31+ it ( 'should successfully render a template with context' , ( ) => {
32+ const templateName = 'Winner' ;
33+ const context = { username : 'Clinton' } ;
34+ const mockHbsContent = 'Hello {{username}}' ;
35+
36+ // Mock fs to say the file exists and return our fake string
37+ jest . spyOn ( fs , 'existsSync' ) . mockReturnValue ( true ) ;
38+ jest . spyOn ( fs , 'readFileSync' ) . mockReturnValue ( mockHbsContent ) ;
39+
40+ const result = service . render ( templateName , context ) ;
41+
42+ expect ( result ) . toBe ( 'Hello Clinton' ) ;
43+ expect ( fs . existsSync ) . toHaveBeenCalled ( ) ;
44+ expect ( fs . readFileSync ) . toHaveBeenCalled ( ) ;
45+ } ) ;
46+
47+ it ( 'should throw InternalServerErrorException if template does not exist' , ( ) => {
48+ jest . spyOn ( fs , 'existsSync' ) . mockReturnValue ( false ) ;
49+
50+ expect ( ( ) => {
51+ service . render ( 'non-existent' , { } ) ;
52+ } ) . toThrow ( InternalServerErrorException ) ;
53+ } ) ;
54+
55+ it ( 'should throw InternalServerErrorException if handlebars fails to compile' , ( ) => {
56+ jest . spyOn ( fs , 'existsSync' ) . mockReturnValue ( true ) ;
57+ jest . spyOn ( fs , 'readFileSync' ) . mockReturnValue ( 'Hello {{username' ) ;
58+
59+ expect ( ( ) => {
60+ service . render ( 'broken-template' , { username : 'Clinton' } ) ;
61+ } ) . toThrow ( InternalServerErrorException ) ;
62+ } ) ;
63+ } ) ;
64+ } ) ;
0 commit comments