@nestjs/common#INestApplication TypeScript Examples

The following examples show how to use @nestjs/common#INestApplication. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From aqualink-app with MIT License 7 votes vote down vote up
mockDeleteFileFalling = (app: INestApplication) => {
  const surveysService = app.get(SurveysService);

  jest
    .spyOn(surveysService.googleCloudService, 'deleteFile')
    .mockImplementation((props: string) =>
      Promise.reject(new Error('Delete file failed')),
    );
}
Example #2
Source File: test-utils.ts    From nestjs-starter-rest-api with MIT License 7 votes vote down vote up
seedAdminUser = async (
  app: INestApplication,
): Promise<{ adminUser: UserOutput; authTokenForAdmin: AuthTokenOutput }> => {
  const defaultAdmin: CreateUserInput = {
    name: 'Default Admin User',
    username: 'default-admin',
    password: 'default-admin-password',
    roles: [ROLE.ADMIN],
    isAccountDisabled: false,
    email: '[email protected]',
  };

  const ctx = new RequestContext();

  // Creating Admin User
  const userService = app.get(UserService);
  const userOutput = await userService.createUser(ctx, defaultAdmin);

  const loginInput: LoginInput = {
    username: defaultAdmin.username,
    password: defaultAdmin.password,
  };

  // Logging in Admin User to get AuthToken
  const loginResponse = await request(app.getHttpServer())
    .post('/auth/login')
    .send(loginInput)
    .expect(HttpStatus.OK);

  const authTokenForAdmin: AuthTokenOutput = loginResponse.body.data;

  const adminUser: UserOutput = JSON.parse(JSON.stringify(userOutput));

  return { adminUser, authTokenForAdmin };
}
Example #3
Source File: test_utils.ts    From nestjs-angular-starter with MIT License 7 votes vote down vote up
/**
 * Returns an already existing instance of nest app, or creates a new one
 * which will be used for other tests as well.
 */
export async function getNestApp(): Promise<INestApplication> {
  if (nestApp) return nestApp;

  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();

  nestApp = moduleFixture.createNestApplication();

  // Add validation and transform pipe
  nestApp.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    }),
  );

  await nestApp.init();
  return nestApp;
}
Example #4
Source File: util.ts    From knests with MIT License 7 votes vote down vote up
getApp = async (): Promise<INestApplication> => {
  if (app !== undefined) return app;
  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();

  app = moduleFixture.createNestApplication();
  app = await app.init();
  return app;
}
Example #5
Source File: app.e2e-spec.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!');
  });
});
Example #6
Source File: swagger.ts    From nestjs-api-example with MIT License 6 votes vote down vote up
/**
 * Swagger 세팅
 *
 * @param {INestApplication} app
 */
export function setupSwagger(app: INestApplication): void {
  const options = new DocumentBuilder()
    .setTitle('NestJS Study API Docs')
    .setDescription('NestJS Study API description')
    .setVersion('1.0.0')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-docs', app, document);
}
Example #7
Source File: app.e2e-test.ts    From nest-react with GNU Lesser General Public License v3.0 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [ConfigModule, StatusModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', async () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello world from Nest running on localhost:4000!');
  });
});
Example #8
Source File: app.e2e-spec.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!');
  });
});
Example #9
Source File: test-auth-utils.ts    From barista with Apache License 2.0 6 votes vote down vote up
export async function getAccessToken(app: INestApplication) {
  const authInfo = {username: 'anyusername', password: 'anypass'};
  const response = await request(app.getHttpServer())
    .post('/user/login')
    .send(authInfo);
  expect(response.status).toBe(HttpStatus.CREATED);
  return response.body.accessToken;
}
Example #10
Source File: runner.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app: INestApplication = await NestFactory.create(
    EventStoreHeroesModule,
    {
      logger: ['log', 'error', 'warn', 'debug', 'verbose'],
    },
  );

  app.useGlobalFilters(new AllExceptionFilter());
  await app.listen(3000, () => {
    console.log('Application is listening on port 3000.');
  });
}
Example #11
Source File: app.e2e-spec.ts    From uniauth-backend with MIT License 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer()).get('/').expect(200).expect('Hello World!');
  });
});
Example #12
Source File: setup.spec.ts    From rewind with MIT License 6 votes vote down vote up
describe("Setup E2E", () => {
  let app: INestApplication;

  beforeAll(async () => {
    // app = await setupBootstrap({ userDataPath: applicationDataPath });
  });

  it("/GET desktop", () => {
    return request(app.getHttpServer())
      .get("/api/desktop")
      .expect(200)
      .then((res) => {
        if (res.ok) {
          console.log("GET /api/desktop\n" + JSON.stringify(res.body));
        }
      });
    // .end((err, res) => {
    // });
  });

  afterAll(async () => {
    await app.close();
  });
});
Example #13
Source File: system.controller.spec.ts    From amplication with Apache License 2.0 6 votes vote down vote up
describe('SystemController', () => {
  let app: INestApplication;

  beforeEach(async () => {
    jest.clearAllMocks();
    const moduleRef = await Test.createTestingModule({
      imports: [MorganModule.forRoot()],
      providers: [
        {
          provide: BuildService,
          useClass: jest.fn(() => ({
            updateRunningBuildsStatus: mockUpdateRunningBuildsStatus
          }))
        },
        {
          provide: DeploymentService,
          useClass: jest.fn(() => ({
            updateRunningDeploymentsStatus: mockUpdateRunningDeploymentsStatus,
            destroyStaledDeployments: mockDestroyStaledDeployments
          }))
        }
      ],
      controllers: [SystemController]
    }).compile();

    app = moduleRef.createNestApplication();
    await app.init();
  });

  it('should update statuses', async () => {
    await request(app.getHttpServer())
      .post('/system/update-statuses')
      .expect(HttpStatus.CREATED);
    expect(mockUpdateRunningBuildsStatus).toBeCalledTimes(1);
    expect(mockUpdateRunningBuildsStatus).toBeCalledWith();
    expect(mockUpdateRunningDeploymentsStatus).toBeCalledTimes(1);
    expect(mockUpdateRunningDeploymentsStatus).toBeCalledWith();
  });
});
Example #14
Source File: health-check.spec.ts    From aqualink-app with MIT License 6 votes vote down vote up
healthCheckTests = () => {
  let app: INestApplication;
  const testService = TestService.getInstance();

  beforeAll(async () => {
    app = await testService.getApp();
  });

  it('GET /health-check.', async () => {
    const rsp = await request(app.getHttpServer()).get('/health-check');
    expect(rsp.body).toStrictEqual({ status: 200 });
  });
}
Example #15
Source File: nest-factory.d.ts    From nest-jaeger with MIT License 6 votes vote down vote up
/**
     * Creates an instance of NestApplication.
     *
     * @param module Entry (root) application module class
     * @param options List of options to initialize NestApplication
     *
     * @returns A promise that, when resolved,
     * contains a reference to the NestApplication instance.
     */
    create<T extends INestApplication = INestApplication>(module: any, options?: NestApplicationOptions): Promise<T>;
Example #16
Source File: app.e2e-spec.ts    From trading-bot with MIT License 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
  })

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!')
  })
})
Example #17
Source File: auto-delete.e2e-spec.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
describe('Auto delete', () => {
  let app: INestApplication;

  beforeEach(async () => {
    app = await createTestModule();
  });

  it('Delete after success upload', () => {
    return request.default(app.getHttpServer())
      .post('/auto-delete-single-file')
      .attach('file', path.resolve(__dirname, 'test-files', 'file.txt'))
      .expect(200)
      .expect((res: any) => {
        expect(typeof res.body.path).toBe('string');
        expect(fs.existsSync(res.body.path)).toBe(false);
      });
  });

  it('Delete after failed upload (class validation)', () => {
    return request.default(app.getHttpServer())
      .post('/auto-delete-single-file')
      .attach('file', path.resolve(__dirname, 'test-files', 'file-large.txt'))
      .expect(400)
      .expect((res: any) => {

        expect(typeof res.body.message[0]).toBe('string');
        expect(fs.existsSync(res.body.message[0])).toBe(false);
      });
  });

});
Example #18
Source File: app.e2e-spec.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer()).get('/').expect(200).expect('Hello World!');
  });
});
Example #19
Source File: graphql.e2e.spec.ts    From nest-casl with MIT License 6 votes vote down vote up
createCaslTestingModule = async (
  caslOptions: OptionsForRoot<Roles>,
  postService: PostService,
  userService: UserService,
): Promise<INestApplication> => {
  const moduleRef = await Test.createTestingModule({
    imports: [
      PostModule,
      UserModule,
      GraphQLModule.forRoot<ApolloDriverConfig>({
        driver: ApolloDriver,
        autoSchemaFile: true,
        playground: false,
        debug: true,
      }),
      CaslModule.forRoot<Roles>(caslOptions),
    ],
  })
    .overrideProvider(PostService)
    .useValue(postService)
    .overrideProvider(UserService)
    .useValue(userService)
    .compile();

  const app = moduleRef.createNestApplication();
  await app.init();
  return app;
}
Example #20
Source File: app.e2e-spec.ts    From aws-nestjs-starter with The Unlicense 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/notification (POST)', () => {
    return request(app.getHttpServer())
      .post('/notification')
      .send({
        targetId: 'device1',
        userId: 'user1',
        content: 'Hello',
      })
      .expect(201);
  });

  it('/notification (GET)', () => {
    return request(app.getHttpServer())
      .get('/notification?userId=dummy')
      .expect(200)
      .expect([]);
  });
});
Example #21
Source File: auth.e2e-spec.ts    From pandaid with MIT License 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AuthModule]
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
  })

  it('/auth/login (POST) - 401', () => {
    return request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: 'invalid', password: 'secret' })
      .expect(401)
  })

  it('/auth/login (POST) - 201', () => {
    return request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: '[email protected]', password: '1' })
      .expect(201)
  })
})
Example #22
Source File: swagger.plugin.ts    From life-helper-backend with MIT License 6 votes vote down vote up
/**
 * 装载 `Swagger`
 *
 * @param app Application 实例
 */
export function setupSwagger(app: INestApplication): void {
  const title = '「我的个人助手」项目 API 文档'
  const description = '「我的个人助手」项目 API 文档,'
  const version = '1.0'

  const config = new DocumentBuilder().setTitle(title).setDescription(description).setVersion(version).build()
  const document = SwaggerModule.createDocument(app, config)

  SwaggerModule.setup('docs', app, document)
}
Example #23
Source File: deposit-heads.service.spec.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
describe('DepositHeadsService', () => {
  let app: INestApplication;
  let depositHeadsService: DepositHeadsService;
  let prisma: PrismaService;

  beforeAll(async () => {
    app = await bootstrapTestApp();
    depositHeadsService = app.get(DepositHeadsService);
    prisma = app.get(PrismaService);
    await app.init();
  });

  afterAll(async () => {
    await app.close();
  });

  describe('upsert', () => {
    it('upserts a DepositHead record', async () => {
      const hash = uuid();
      const record = await depositHeadsService.upsert(hash, prisma);
      expect(record).toMatchObject({
        id: 1,
        block_hash: hash,
      });
    });
  });
});
Example #24
Source File: debug.module.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
static graph(app: INestApplication): void {
    /**
     * Build the tree:
     * 1. Find the AppModule
     * 2. Recursively browse its imports and
     * 3. Ignore core modules attached to each module like "InternalCoreModule" and "ConfigHostModule"
     */
    const container = app.get(ModulesContainer);
    const moduleWrappers = Array.from(container.values());
    const appModule = moduleWrappers.find(
      (moduleWrapper) => moduleWrapper.metatype.name === 'CoreModule',
    );
    const tree = getTree(appModule);

    // Add the routes
    const basePath = '/dependency-graph';
    const adapter = app.getHttpAdapter();
    adapter.get(`${basePath}/data`, (req: Request, res: Response) => {
      return res.json(tree);
    });
    adapter.get(`${basePath}/index.html`, (req: Request, res: Response) => {
      res.sendFile(join(__dirname, 'static', 'index.html'));
    });
    adapter.get(`${basePath}/main.js`, (req: Request, res: Response) => {
      res.sendFile(join(__dirname, 'static', 'main.js'));
    });
  }
Example #25
Source File: app.e2e-spec.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication

  beforeAll(async (done) => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()

    done()
  })

  it('/ (GET)', (done) => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!')
      .end(() => done())
  })

  afterAll(async (done) => {
    await firebaseAdmin.app().delete()
    await app.close()
    done()
  })
})
Example #26
Source File: mikro-orm.middleware.test.ts    From nestjs with MIT License 6 votes vote down vote up
describe('Middleware executes request context for all MikroORM registered', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [TestModule],
    }).compile();

    app = moduleFixture.createNestApplication();

    await app.init();
  });

  it(`forRoutes(/foo) should return 'true'`, () => {
    return request(app.getHttpServer()).get('/foo').expect(200, 'true');
  });

  it(`forRoutes(/bar) should return 'true'`, () => {
    return request(app.getHttpServer()).get('/foo').expect(200, 'true');
  });

  afterAll(async () => {
    await app.close();
  });
});
Example #27
Source File: app.e2e-spec.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    await resetDBBeforeTest();
    await createDBEntities();

    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleRef.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!');
  });

  afterAll(async () => {
    await app.close();
    await closeDBAfterTest();
  });
});
Example #28
Source File: cat-tenancy.spec.ts    From nestjs-tenancy with MIT License 6 votes vote down vote up
describe('CatTenancy', () => {
    let server: Server;
    let app: INestApplication;

    beforeEach(async () => {
        const module = await Test.createTestingModule({
            imports: [AppModule],
        }).compile();

        app = module.createNestApplication();
        server = app.getHttpServer();
        await app.init();
    });

    it(`should return created document`, (done) => {
        const createDto = { name: 'Nest', breed: 'Maine coon', age: 5 };
        request(server)
            .post('/cats')
            .set('X-TENANT-ID', 'cats')
            .send(createDto)
            .expect(201)
            .end((err, { body }) => {
                expect(body.name).toEqual(createDto.name);
                expect(body.age).toEqual(createDto.age);
                expect(body.breed).toEqual(createDto.breed);
                done();
            });
    });

    afterEach(async () => {
        await app.close();
    });
});
Example #29
Source File: electron.e2e.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
describe('ElectronModule', () => {
    let app: INestApplication;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            imports: [
                ConfigModule.forRoot({
                    isGlobal: true,
                    load: [configuration],
                }),
                ElectronModule,
            ],
        }).compile();

        app = module.createNestApplication();
        await app.init();
    });

    it('SystemProvider should be defined', () => {
        expect(app).toBeDefined();

        const provider = app.get(SystemProvider);

        expect(provider).toBeDefined();
    });
});