supertest#agent TypeScript Examples

The following examples show how to use supertest#agent. 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: denoService.test.ts    From farrow with MIT License 6 votes vote down vote up
describe('deno-api', () => {
  it('client in server services', async () => {
    const http = createHttp()

    http.route('/counter').use(CounterService)

    const server = http.listen(3000)

    const source = fs.readFileSync(`${__dirname}/client.ts`, 'utf-8')

    const test = await agent(server).get('/counter/client.ts').send()

    server.close()

    expect(test.text.replace(/\r|\n/g, '')).toBe(source.replace(/\r|\n/g, ''))
  })

  it('should work', async () => {
    global.fetch = fetch as any
    const http = createHttp()

    http.route('/counter').use(CounterService)

    const server = http.listen(3000)

    expect(await api.getCount({})).toStrictEqual({ count: 0 })

    expect(await api.setCount({ newCount: 1 })).toStrictEqual({ count: 1 })

    expect(await api.getCount({})).toStrictEqual({ count: 1 })

    server.close()
  })
})
Example #2
Source File: app.spec.ts    From bootcamp-devops-lemoncode with MIT License 5 votes vote down vote up
describe('/api/', () => {
  describe('GET verb', () => {
    it('should return todos', async (done) => {
      // Arrange
      server = await app.listen(process.env.PORT);
      request = agent(server);

      // Act
      const response = await request.get('/api/');
      const todos = response.body;

      // Assert
      expect(todos.length).toBe(3);
      removeServer(done);
    });
  });

  describe('GET verb with id parameter', () => {
    it('should returna single todo', async (done) => {
      // Arrange
      server = await app.listen(process.env.PORT);
      request = agent(server);

      // Act
      const response = await request.get('/api/1/');
      const todo = response.body;

      // Assert
      expect(todo.id).toBe(1);
      expect(todo.title).toBe('Learn node, please!!');
      removeServer(done);
    });
  });

  describe('POST verb creates a new todo', () => {
    it('should create a new todo', async (done) => {
      // Arrange
      const todo: TodoModel = {
        id: 0,
        title: 'New Todo',
        completed: false,
        dueDate: '2020-11-27',
      };

      // Act
      const response = await request.post('/api/').send(todo);

      // Assert
      expect(response.status).toBe(201);
      removeServer(done);
    });
  });
});
Example #3
Source File: app.test.ts    From bootcamp-devops-lemoncode with MIT License 5 votes vote down vote up
beforeEach(async () => {
  server = await app.listen(process.env.PORT);
  request = agent(server);
  await Knex.from('todos').delete();
});
Example #4
Source File: TestApiServer.ts    From l2beat with MIT License 5 votes vote down vote up
export function createTestApiServer(routers: Router[]) {
  const callback = new ApiServer(0, Logger.SILENT, routers).getNodeCallback()
  return agent(callback)
}
Example #5
Source File: server.spec.ts    From cli with Apache License 2.0 4 votes vote down vote up
describe('server', () => {
  const OLD_ENV = process.env;

  const setInvalidEnvironmentVariables = () => {
    process.env.ORGANIZATION_ID = undefined;
    process.env.API_KEY = undefined;
    process.env.USER_EMAIL = undefined;
  };

  const setValidEnvironmentVariables = () => {
    process.env.PLATFORM_URL = 'https://platform.cloud.coveo.com';
    process.env.ORGANIZATION_ID = 'my-org';
    process.env.API_KEY = 'xxx';
    process.env.USER_EMAIL = '[email protected]';
  };

  const triggerAMiddlewareError = () => {
    mockedMiddleware.mockImplementationOnce(
      (_req: Request, _res: Response, next: NextFunction) => {
        const err: Error = new Error();
        next(err);
      }
    );
  };

  const resetAppLocals = () => {
    mockedMiddleware.mockImplementationOnce(
      (req: Request, _res: Response, _next: NextFunction) => {
        delete req.app.locals.platform;
      }
    );
  };

  const doMockPlatformClient = () => {
    mockedPlatformClient.mockImplementation(
      () =>
        ({
          search: {
            createToken: mockedCreateToken,
          },
        } as unknown as PlatformClient)
    );
  };

  beforeEach(() => {
    jest.resetModules();
    process.env = {...OLD_ENV};
    doMockPlatformClient();
  });

  afterAll(() => {
    process.env = OLD_ENV;
  });

  describe('when an unknown error happens', () => {
    beforeEach(() => {
      setValidEnvironmentVariables();
      triggerAMiddlewareError();
    });

    it('should return a generic error message', async () => {
      const res = await agent(app).get('/token');
      expect(res.body.message).toEqual('Something broke!');
    });
  });

  describe('when required environment variables are missing', () => {
    beforeEach(() => {
      setInvalidEnvironmentVariables();
    });

    it('should return a JSON response', async () => {
      await agent(app).get('/token').expect('Content-Type', /json/);
    });

    it('should return an error with a message', async () => {
      const res = await agent(app).get('/token');

      expect(res.serverError).toBeTruthy();
      expect(res.body.message).toEqual(
        'Make sure to configure the environment variables in the ".env" file. Refer to the README to set up the server.'
      );
    });
  });

  describe('when the API key does not have the right privileges', () => {
    beforeEach(() => {
      setValidEnvironmentVariables();

      mockedCreateToken.mockRejectedValueOnce({
        statusCode: 403,
        message: 'Forbidden',
        type: 'AccessDeniedException',
      });
    });

    it('it should return an error', async () => {
      const res = await agent(app).get('/token');
      expect(res.status).toBe(403);
      expect(res.body).not.toHaveProperty('token');
    });
  });

  describe('when the environment variables are correctly set', () => {
    beforeEach(() => {
      setValidEnvironmentVariables();
      resetAppLocals();

      mockedCreateToken.mockResolvedValueOnce({
        token: 'this.is.a.search.token',
      });
    });

    it('should correctly initialize the #platformClient based on environment variables', async () => {
      await agent(app).get('/token');
    });

    it('should correctly initialize the #platformClient based on environment variables', async () => {
      await agent(app).get('/token');
      expect(mockedPlatformClient).toHaveBeenLastCalledWith(
        expect.objectContaining({
          accessToken: 'xxx',
          host: 'https://platform.cloud.coveo.com',
          organizationId: 'my-org',
        })
      );
    });

    it('should return JSON response', async () => {
      await agent(app).get('/token').expect('Content-Type', /json/);
    });

    it('should not create multiple instances of #platformClient', async () => {
      await agent(app).get('/token');
      await agent(app).get('/token');
      await agent(app).get('/token');
      expect(mockedPlatformClient).toHaveBeenCalledTimes(1);
    });

    it('should correctly call #createToken with the appropriate arguments', async () => {
      await agent(app).get('/token');
      expect(mockedCreateToken).toHaveBeenLastCalledWith(
        expect.objectContaining({
          userIds: [
            {
              name: '[email protected]',
              provider: 'Email Security Provider',
              type: RestUserIdType.User,
            },
          ],
        })
      );
    });

    it('should return a search token', async () => {
      const res = await agent(app).get('/token');
      expect(res.status).toBe(200);
      expect(res.body).toEqual({token: 'this.is.a.search.token'});
    });
  });
});