Skip to content

Replies as Promises #1557

@mgcrea

Description

@mgcrea

Context

Writing jest mocks for a got client (eg. got.extend()), was looking into dynamically loaded fixtures as replies. Found out that promises and async/await functions where not handled properly.

Alternatives

Force the code to be synchronous (doable in my case with the fs package).

Has the feature been requested before?

Did not found it

If the feature request is accepted, would you be willing to submit a PR?

Yes, added unit tests already, but had a look at the code and did not found it trivial to add it. Found that there was no async handling (only setting this.body) and did not really found out where the Promise.resolve() could fit, any guidance/ideas would be great.

Example

A few tests:

test('reply can take a promise', async t => {
  const scope = nock('http://example.com')
    .get('/')
    .reply(200, async (path, requestBody, callback) => 'Hello World!')

  const response = await got('http://example.com/', {
    encoding: null,
  })

  scope.done()
  t.type(response.body, Buffer)
  t.equal(response.body.toString('utf8'), 'Hello World!')
})

test('reply takes a promise for status code', async t => {
  const expectedStatusCode = 202
  const responseBody = 'Hello, world!'
  const headers = {
    'X-Custom-Header': 'abcdef',
  }

  const scope = nock('http://example.com')
    .get('/')
    .reply(async (path, requestBody, cb) => {
      await new Promise((resolve, reject) => {
        setTimeout(resolve, 1)
      })
      return [expectedStatusCode, responseBody, headers]
    })

  const response = await got('http://example.com/')

  t.equal(response.statusCode, expectedStatusCode, 'sends status code')
  t.deepEqual(response.headers, headers, 'sends headers')
  t.equal(response.body, responseBody, 'sends request body')
  scope.done()
})

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions