app.controller.spec.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Test, TestingModule } from '@nestjs/testing'
  2. import { AppController } from './app.controller'
  3. import { AppService } from './app.service'
  4. class MockResponse {
  5. res: any
  6. constructor() {
  7. this.res = {}
  8. }
  9. status = jest
  10. .fn()
  11. .mockReturnThis()
  12. .mockImplementationOnce((code) => {
  13. this.res.code = code
  14. return this
  15. })
  16. send = jest
  17. .fn()
  18. .mockReturnThis()
  19. .mockImplementationOnce((message) => {
  20. this.res.message = message
  21. return this
  22. })
  23. json = jest
  24. .fn()
  25. .mockReturnThis()
  26. .mockImplementationOnce((json) => {
  27. this.res.json = json
  28. return this
  29. })
  30. }
  31. describe('AppController', () => {
  32. let appController: AppController
  33. let appService: AppService
  34. const response = new MockResponse()
  35. beforeEach(async () => {
  36. const app: TestingModule = await Test.createTestingModule({
  37. controllers: [AppController],
  38. providers: [
  39. {
  40. provide: AppService,
  41. useValue: {
  42. getHello: jest.fn(() => {}),
  43. getSecureResource: jest.fn(() => {})
  44. }
  45. }
  46. ]
  47. }).compile()
  48. appController = app.get<AppController>(AppController)
  49. appService = app.get<AppService>(AppService)
  50. })
  51. describe('root', () => {
  52. it('should be defined', () => {
  53. expect(appController).toBeDefined()
  54. })
  55. it('should call method getHello() in AppService', () => {
  56. const createSpy = jest.spyOn(appService, 'getHello')
  57. appController.getHello(response as any)
  58. expect(createSpy).toHaveBeenCalled()
  59. })
  60. it('should call method getProtectedResource() in AppService', () => {
  61. const createSpy = jest.spyOn(appService, 'getSecureResource')
  62. appController.getProtectedResource(response as any)
  63. expect(createSpy).toHaveBeenCalled()
  64. })
  65. })
  66. })