supertest#Response TypeScript Examples

The following examples show how to use supertest#Response. 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: test-utils.ts    From office-booker with MIT License 6 votes vote down vote up
expectOk = (response: Response) => {
  if (!response.ok) {
    throw new Error(`Response not okay: ${response.status}\n${response.body}`);
  }
}
Example #2
Source File: test-utils.ts    From office-booker with MIT License 6 votes vote down vote up
expectUnauthorized = (response: Response) => {
  expect(response.status).toBe(401);
  expect(response.body).toMatchObject({
    message: 'Unauthorized',
  });
  expect(Object.keys(response.body)).toEqual(['message', 'reference', 'error']);
}
Example #3
Source File: test-utils.ts    From office-booker with MIT License 6 votes vote down vote up
expectForbidden = (response: Response) => {
  expect(response.status).toBe(403);
  expect(response.body).toMatchObject({
    message: 'Forbidden',
  });
  expect(Object.keys(response.body)).toEqual(['message', 'reference', 'error']);
}
Example #4
Source File: apicalls.ts    From WebdriverIOTypeScriptE2E with MIT License 5 votes vote down vote up
makeGETCall = async (endpoint: endpoints | string, payload?: object, headers?: object): Promise<Response> => {
    if (payload && headers) return request.get(endpoint).set(headers).send(payload);
    else if (payload) return request.get(endpoint).send(payload);
    else return request.get(endpoint);
}
Example #5
Source File: apicalls.ts    From WebdriverIOTypeScriptE2E with MIT License 5 votes vote down vote up
makePOSTCall = async (endpoint: endpoints | string, payload: string | object, headers?: object): Promise<Response> => {
    if (headers) return request.post(endpoint).set(headers);
    return request.post(endpoint).send(payload);
}
Example #6
Source File: apicalls.ts    From WebdriverIOTypeScriptE2E with MIT License 5 votes vote down vote up
makeDELETECall = async (endpoint: endpoints | string, payload?: object): Promise<Response> => {
    if (payload) return request.delete(endpoint).send(payload);
    return request.delete(endpoint);
}
Example #7
Source File: createPermissionIntegrationRouter.test.ts    From backstage with Apache License 2.0 4 votes vote down vote up
describe('createPermissionIntegrationRouter', () => {
  let app: Express;
  let router: Router;

  beforeAll(() => {
    router = createPermissionIntegrationRouter({
      resourceType: 'test-resource',
      getResources: mockGetResources,
      rules: [testRule1, testRule2],
    });

    app = express().use(router);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('works', async () => {
    expect(router).toBeDefined();
  });

  describe('POST /.well-known/backstage/permissions/apply-conditions', () => {
    it.each([
      {
        rule: 'test-rule-1',
        resourceType: 'test-resource',
        params: ['abc', 123],
      },
      {
        anyOf: [
          {
            rule: 'test-rule-1',
            resourceType: 'test-resource',
            params: ['a', 1],
          },
          { rule: 'test-rule-2', resourceType: 'test-resource', params: [{}] },
        ],
      },
      {
        not: {
          rule: 'test-rule-2',
          resourceType: 'test-resource',
          params: [{}],
        },
      },
      {
        allOf: [
          {
            anyOf: [
              {
                rule: 'test-rule-1',
                resourceType: 'test-resource',
                params: ['a', 1],
              },
              {
                rule: 'test-rule-2',
                resourceType: 'test-resource',
                params: [{}],
              },
            ],
          },
          {
            not: {
              allOf: [
                {
                  rule: 'test-rule-1',
                  resourceType: 'test-resource',
                  params: ['b', 2],
                },
                {
                  rule: 'test-rule-2',
                  resourceType: 'test-resource',
                  params: [{ c: 3 }],
                },
              ],
            },
          },
        ],
      },
    ])('returns 200/ALLOW when criteria match (case %#)', async conditions => {
      const response = await request(app)
        .post('/.well-known/backstage/permissions/apply-conditions')
        .send({
          items: [
            {
              id: '123',
              resourceRef: 'default:test/resource',
              resourceType: 'test-resource',
              conditions,
            },
          ],
        });

      expect(response.status).toEqual(200);
      expect(response.body).toEqual({
        items: [
          {
            id: '123',
            result: AuthorizeResult.ALLOW,
          },
        ],
      });
    });

    it.each([
      {
        rule: 'test-rule-2',
        resourceType: 'test-resource',
        params: [{ foo: 0 }],
      },
      {
        allOf: [
          {
            rule: 'test-rule-1',
            resourceType: 'test-resource',
            params: ['a', 1],
          },
          { rule: 'test-rule-2', resourceType: 'test-resource', params: [{}] },
        ],
      },
      {
        allOf: [
          {
            anyOf: [
              {
                rule: 'test-rule-1',
                resourceType: 'test-resource',
                params: ['a', 1],
              },
              {
                rule: 'test-rule-2',
                resourceType: 'test-resource',
                params: [{ b: 2 }],
              },
            ],
          },
          {
            not: {
              allOf: [
                {
                  rule: 'test-rule-1',
                  resourceType: 'test-resource',
                  params: ['c', 3],
                },
                {
                  not: {
                    rule: 'test-rule-2',
                    resourceType: 'test-resource',
                    params: [{ d: 4 }],
                  },
                },
              ],
            },
          },
        ],
      },
    ])(
      'returns 200/DENY when criteria do not match (case %#)',
      async conditions => {
        const response = await request(app)
          .post('/.well-known/backstage/permissions/apply-conditions')
          .send({
            items: [
              {
                id: '123',
                resourceRef: 'default:test/resource',
                resourceType: 'test-resource',
                conditions,
              },
            ],
          });

        expect(response.status).toEqual(200);
        expect(response.body).toEqual({
          items: [{ id: '123', result: AuthorizeResult.DENY }],
        });
      },
    );

    describe('batched requests', () => {
      let response: Response;

      beforeEach(async () => {
        response = await request(app)
          .post('/.well-known/backstage/permissions/apply-conditions')
          .send({
            items: [
              {
                id: '123',
                resourceRef: 'default:test/resource-1',
                resourceType: 'test-resource',
                conditions: {
                  rule: 'test-rule-1',
                  resourceType: 'test-resource',
                  params: [],
                },
              },
              {
                id: '234',
                resourceRef: 'default:test/resource-1',
                resourceType: 'test-resource',
                conditions: {
                  rule: 'test-rule-2',
                  resourceType: 'test-resource',
                  params: [],
                },
              },
              {
                id: '345',
                resourceRef: 'default:test/resource-2',
                resourceType: 'test-resource',
                conditions: {
                  not: {
                    rule: 'test-rule-1',
                    resourceType: 'test-resource',
                    params: [],
                  },
                },
              },
              {
                id: '456',
                resourceRef: 'default:test/resource-3',
                resourceType: 'test-resource',
                conditions: {
                  not: {
                    rule: 'test-rule-2',
                    resourceType: 'test-resource',
                    params: [],
                  },
                },
              },
              {
                id: '567',
                resourceRef: 'default:test/resource-4',
                resourceType: 'test-resource',
                conditions: {
                  anyOf: [
                    {
                      rule: 'test-rule-1',
                      resourceType: 'test-resource',
                      params: [],
                    },
                    {
                      rule: 'test-rule-2',
                      resourceType: 'test-resource',
                      params: [],
                    },
                  ],
                },
              },
            ],
          });
      });

      it('processes batched requests', () => {
        expect(response.status).toEqual(200);
        expect(response.body).toEqual({
          items: [
            { id: '123', result: AuthorizeResult.ALLOW },
            { id: '234', result: AuthorizeResult.DENY },
            { id: '345', result: AuthorizeResult.DENY },
            { id: '456', result: AuthorizeResult.ALLOW },
            { id: '567', result: AuthorizeResult.ALLOW },
          ],
        });
      });

      it('calls getResources for all required resources at once', () => {
        expect(mockGetResources).toHaveBeenCalledWith([
          'default:test/resource-1',
          'default:test/resource-2',
          'default:test/resource-3',
          'default:test/resource-4',
        ]);
      });
    });

    it('returns 400 when called with incorrect resource type', async () => {
      const response = await request(app)
        .post('/.well-known/backstage/permissions/apply-conditions')
        .send({
          items: [
            {
              id: '123',
              resourceRef: 'default:test/resource-1',
              resourceType: 'test-incorrect-resource-1',
              conditions: {
                rule: 'test-rule-1',
                resourceType: 'test-incorrect-resource-1',
                params: [{}],
              },
            },
            {
              id: '234',
              resourceRef: 'default:test/resource-2',
              resourceType: 'test-resource',
              conditions: {
                rule: 'test-rule-1',
                resourceType: 'test-resource',
                params: [{}],
              },
            },
            {
              id: '345',
              resourceRef: 'default:test/resource-3',
              resourceType: 'test-incorrect-resource-2',
              conditions: {
                rule: 'test-rule-1',
                resourceType: 'test-incorrect-resource-2',
                params: [{}],
              },
            },
          ],
        });

      expect(response.status).toEqual(400);
      expect(response.error && response.error.text).toMatch(
        /unexpected resource types: test-incorrect-resource-1, test-incorrect-resource-2/i,
      );
    });

    it('returns 200/DENY when resource is not found', async () => {
      mockGetResources.mockImplementationOnce(async resourceRefs =>
        resourceRefs.map(() => undefined),
      );

      const response = await request(app)
        .post('/.well-known/backstage/permissions/apply-conditions')
        .send({
          items: [
            {
              id: '123',
              resourceRef: 'default:test/resource',
              resourceType: 'test-resource',
              conditions: {
                rule: 'test-rule-1',
                resourceType: 'test-resource',
                params: [],
              },
            },
          ],
        });

      expect(response.status).toEqual(200);
      expect(response.body).toEqual({
        items: [
          {
            id: '123',
            result: AuthorizeResult.DENY,
          },
        ],
      });
    });

    it('interleaves responses for present and missing resources', async () => {
      mockGetResources.mockImplementationOnce(async resourceRefs =>
        resourceRefs.map(resourceRef =>
          resourceRef === 'default:test/missing-resource'
            ? undefined
            : { id: resourceRef },
        ),
      );

      const response = await request(app)
        .post('/.well-known/backstage/permissions/apply-conditions')
        .send({
          items: [
            {
              id: '123',
              resourceRef: 'default:test/resource-1',
              resourceType: 'test-resource',
              conditions: {
                rule: 'test-rule-1',
                resourceType: 'test-resource',
                params: [],
              },
            },
            {
              id: '234',
              resourceRef: 'default:test/missing-resource',
              resourceType: 'test-resource',
              conditions: {
                rule: 'test-rule-1',
                resourceType: 'test-resource',
                params: [],
              },
            },
            {
              id: '345',
              resourceRef: 'default:test/resource-2',
              resourceType: 'test-resource',
              conditions: {
                rule: 'test-rule-1',
                resourceType: 'test-resource',
                params: [],
              },
            },
          ],
        });

      expect(response.status).toEqual(200);
      expect(response.body).toEqual({
        items: [
          {
            id: '123',
            result: AuthorizeResult.ALLOW,
          },
          {
            id: '234',
            result: AuthorizeResult.DENY,
          },
          {
            id: '345',
            result: AuthorizeResult.ALLOW,
          },
        ],
      });
    });

    it.each([
      undefined,
      '',
      {},
      { resourceType: 'test-resource-type' },
      [{ resourceType: 'test-resource-type' }],
      { items: [{ resourceType: 'test-resource-type' }] },
      { items: [{ resourceRef: 'test/resource-ref' }] },
      {
        items: [
          {
            resourceType: 'test-resource-type',
            resourceRef: 'test/resource-ref',
          },
        ],
      },
      { items: [{ conditions: { anyOf: [] } }] },
      {
        items: [
          { conditions: { rule: 'TEST_RULE', resourceType: 'test-resource' } },
        ],
      },
      { items: [{ conditions: { rule: 'TEST_RULE', params: ['foo'] } }] },
      {
        items: [
          { conditions: { resourceType: 'test-resource', params: ['foo'] } },
        ],
      },
    ])(`returns 400 for invalid input %#`, async input => {
      const response = await request(app)
        .post('/.well-known/backstage/permissions/apply-conditions')
        .send(input);

      expect(response.status).toEqual(400);
      expect(response.error && response.error.text).toMatch(/invalid/i);
    });
  });
});
Example #8
Source File: federation.test.ts    From farrow with MIT License 4 votes vote down vote up
describe('farrow-federation', () => {
  const http = Http()

  http.route('/foo').use(foo)
  http.route('/bar').use(bar)
  http.use(baz)

  it('Introspection', async () => {
    const federationService = await createFederationServices(
      [
        {
          url: '/foo',
          namespace: 'foo',
        },
        {
          url: '/bar',
          namespace: 'bar',
        },
        {
          url: '/greet',
          namespace: 'greet',
        },
        {
          url: '/todo',
          namespace: 'todo',
        },
      ],
      {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        fetch: async (input, init) => {
          const getRes = () =>
            new Promise<Response>((resolve) =>
              supertest(http.server())
                .post(input as string)
                .send(JSON.parse(init!.body! as any))
                .then(resolve),
            )
          const res = await getRes()
          return {
            json() {
              return JSON.parse(res.text)
            },
          }
        },
      },
    )

    const server = Http()

    server.use(federationService)
    const res = await supertest(server.handle).post('/').send({
      type: 'Introspection',
    })

    expect(res.body).toMatchSnapshot()
  })

  it('pass through', async () => {
    const federationService = await createFederationServices(
      [
        {
          url: '/foo',
          namespace: 'foo',
        },
        {
          url: '/bar',
          namespace: 'bar',
        },
        {
          url: '/greet',
          namespace: 'greet',
        },
        {
          url: '/todo',
          namespace: 'todo',
        },
      ],
      {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        fetch: async (input, init) => {
          const getRes = () =>
            new Promise<Response>((resolve) =>
              supertest(http.server())
                .post(input as string)
                .send(JSON.parse(init!.body! as any))
                .then(resolve),
            )
          const res = await getRes()
          return {
            json() {
              return JSON.parse(res.text)
            },
          }
        },
      },
    )

    const server = Http()

    server.use(federationService)
    const res = await supertest(server.handle)
      .post('/')
      .send({
        type: 'Single',
        path: ['foo', 'getTodos'],
        input: { id: 'foo' },
      })

    expect(res.body.type).toBe('ApiSuccessResponse')
    expect(typeof res.body.output).toBe('object')
    expect(Array.isArray(res.body.output.todos)).toBeTruthy()
    expect(res.body.output.todos.length).toBe(3)
  })

  it('mutiple', async () => {
    const federationService = await createFederationServices(
      [
        {
          url: '/foo',
          namespace: 'foo',
        },
        {
          url: '/bar',
          namespace: 'bar',
        },
        {
          url: '/greet',
          namespace: 'greet',
        },
        {
          url: '/todo',
          namespace: 'todo',
        },
      ],
      {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        fetch: async (input, init) => {
          const getRes = () =>
            new Promise<Response>((resolve) =>
              supertest(http.server())
                .post(input as string)
                .send(JSON.parse(init!.body! as any))
                .then(resolve),
            )
          const res = await getRes()
          return {
            json() {
              return JSON.parse(res.text)
            },
          }
        },
      },
    )

    const server = Http()

    server.use(federationService)
    const res = await supertest(server.handle)
      .post('/')
      .send({
        type: 'Single',
        path: ['bar', 'getTodos'],
        input: { id: 'foo' },
      })

    expect(res.body.type).toBe('ApiSuccessResponse')
    expect(typeof res.body.output).toBe('object')
    expect(Array.isArray(res.body.output.todos)).toBeTruthy()
    expect(res.body.output.todos.length).toBe(3)
  })

  it('nest', async () => {
    const federationService = await createFederationServices(
      [
        {
          url: '/foo',
          namespace: 'foo',
        },
        {
          url: '/bar',
          namespace: 'bar',
        },
        {
          url: '/greet',
          namespace: 'greet',
        },
        {
          url: '/todo',
          namespace: 'todo',
        },
      ],
      {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        fetch: async (input, init) => {
          const getRes = () =>
            new Promise<Response>((resolve) =>
              supertest(http.server())
                .post(input as string)
                .send(JSON.parse(init!.body! as any))
                .then(resolve),
            )
          const res = await getRes()
          return {
            json() {
              return JSON.parse(res.text)
            },
          }
        },
      },
    )

    const server = Http()

    server.use(federationService)
    const res = await supertest(server.handle)
      .post('/')
      .send({
        type: 'Single',
        path: ['greet', 'greet'],
        input: { name: 'farrow' },
      })

    expect(res.body.type).toBe('ApiSuccessResponse')
    expect(typeof res.body.output).toBe('object')
    expect(res.body.output.greet).toBe('Hello farrow!')
  })
})