mswjs / source

Generate MSW request handlers from various sources (HAR files, OpenAPI documents, etc).
https://source.mswjs.io
MIT License
142 stars 6 forks source link

Traffic: [Status 304] - Response with null body status cannot have body #52

Open JeanDamien opened 3 months ago

JeanDamien commented 3 months ago

Description

If the user uses a .har file that contained a resource with a 304 status , this package will throw an exception:

Uncaught (in promise) TypeError: Failed to construct 'Response': Response with null body status cannot have body
    at toResponse (@mswjs_source_traffic.js)
    at fromTraffic (@mswjs_source_traffic.js)

https://github.com/mswjs/source/blob/main/src/traffic/utils/har-utils.ts#L40

Reproduction steps

HAR file

test/traffic/fixtures/archives/entry-with-status-304.har

Test template

  // Happen when the resource is already in cache
  it.todo(
    'does not throw an exception given an HAR file with a 304 status entry',
    () => {
      const traffic = readArchive(
        'test/traffic/fixtures/archives/entry-with-status-304.har',
      )
      expect(() => fromTraffic(traffic)).not.toThrow()
    },
  )

Expected behavior

It would be ideal if the library didn't throw an exception, or if we could add an entry in the documentation advising users to clear the cache before generating the HAR file to avoid this issue.

Initial assessment

Browsers, despite the specification stating that a 304 Not Modified response should not include a response body, might display a response body in the network tab for a few practical reasons related to implementation details, user experience, and debugging purposes. These responses do end up in the HAR file.