How to implement integration testing for guards in nest js?

I want to implement unit testing for guards using nest js(Jest JS). I could nt find much documentation.

import {Test, TestingModule} from '@nestjs/testing';
import {CatsController} from '../src/modules/cats/cats.controller';
import {CatsService} from '../src/modules/cats/cats.service';
import {ICat} from '../src/modules/cats/interfaces/ICat';
import {JwtStrategy} from '../src/strategy/AppId.strategy';

  beforeEach(async () => {
     const module = await Test.createTestingModule({
             controllers: [CatsController],
             providers: [CatsService],
         }).compile();

    catsService = module.get<CatsService>(CatsService);
    catsController = module.get<CatsController>(CatsController);

  });
  describe('findAll', () => {
    it('should return an array of cats', async () => {
      // const appIdAuthContext: AppIDAuthToken = tokenInfo;
      const result: ICat = {
        name: 'test',
        age: 1,
        breed: 'one'
      };
      jest.spyOn(catsService, 'findAll').mockImplementation(() => result);
      console.log(result);
      console.log(catsController.findAll());
      expect(await catsController.findAll()).toBe(result);
    });
  });

The above code will return array of cats. i want to implement guards for this unit test.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I have found an implementation.i’m sharing the sample , it may help somebody

function createTestModule() {
      return Test.createTestingModule({
        imports: [
          PassportModule.register({defaultStrategy: 'jwt'}), CatsModule
        ],
        controllers: [
          AppController
        ],
        providers: [
          AppService, RoleGuard, JwtStrategy
        ],
        exports: [PassportModule]
      }).compile();
    }

beforeEach(async () => {
  const module = (await createTestModule(
    ));
  app = module.createNestApplication();
  server = app.getHttpServer();
  await app.init();
});

  it('Should create cat for admin', async () => {
    return await request(server)
        .post('/cats/createcat')
        .set('Authorization', catAdminToken)
        .set('Accept', 'application/json')
        .send(catDto)
        .expect(201);
  });

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply