Skip to content

Commit

Permalink
feat(net-stubbing): automatically parse JSON req/res bodies (#9280)
Browse files Browse the repository at this point in the history
  • Loading branch information
flotwig committed Nov 23, 2020
1 parent 8b78af3 commit 6ee7a9c
Show file tree
Hide file tree
Showing 7 changed files with 160 additions and 4 deletions.
1 change: 1 addition & 0 deletions packages/driver/cypress/fixtures/invalid.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ foo:::: }
1 change: 1 addition & 0 deletions packages/driver/cypress/fixtures/json.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "foo": "bar" }
124 changes: 122 additions & 2 deletions packages/driver/cypress/integration/commands/net_stubbing_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,70 @@ describe('network stubbing', { retries: 2 }, function () {
})
})

context('body parsing', function () {
it('automatically parses JSON request bodies', function () {
const p = Promise.defer()

cy.http('/post-only', (req) => {
expect(req.body).to.deep.eq({ foo: 'bar' })

p.resolve()
}).as('post')
.then(() => {
return $.ajax({
url: '/post-only',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ foo: 'bar' }),
})
}).then((responseText) => {
expect(responseText).to.include('request body:<br>{"foo":"bar"}')

return p
})
.wait('@post').its('request.body').should('deep.eq', { foo: 'bar' })
})

it('doesn\'t automatically parse JSON request bodies if content-type is wrong', function () {
const p = Promise.defer()

cy.http('/post-only', (req) => {
expect(req.body).to.deep.eq(JSON.stringify({ foo: 'bar' }))

p.resolve()
}).as('post')
.then(() => {
return $.ajax({
url: '/post-only',
method: 'POST',
contentType: 'text/html',
data: JSON.stringify({ foo: 'bar' }),
})
}).wrap(p)
.wait('@post').its('request.body').should('eq', JSON.stringify({ foo: 'bar' }))
})

it('sets body to string if JSON is malformed', function () {
const p = Promise.defer()

cy.http('/post-only', (req) => {
expect(req.body).to.deep.eq('{ foo::: }')

p.resolve()
}).as('post')
.then(() => {
return $.ajax({
url: '/post-only',
method: 'POST',
contentType: 'application/json',
// invalid JSON
data: '{ foo::: }',
}).catch(() => p)
})
.wait('@post').its('request.body').should('deep.eq', '{ foo::: }')
})
})

context('matches requests as expected', function () {
it('handles querystrings as expected', function () {
cy.http({
Expand Down Expand Up @@ -1129,7 +1193,7 @@ describe('network stubbing', { retries: 2 }, function () {
it('receives the original response in handler', function (done) {
cy.http('/json-content-type', function (req) {
req.reply(function (res) {
expect(res.body).to.eq('{}')
expect(res.body).to.deep.eq({})

done()
})
Expand Down Expand Up @@ -1347,6 +1411,62 @@ describe('network stubbing', { retries: 2 }, function () {
cy.contains('{"foo":1,"bar":{"baz":"cypress"}}')
})

context('body parsing', function () {
it('automatically parses JSON response bodies', function () {
const p = Promise.defer()

cy.http('/foo.bar.baz.json', (req) => {
req.reply((res) => {
expect(res.body).to.deep.eq({ quux: 'quuz' })
p.resolve()
})
}).as('get')
.then(() => {
return $.get('/fixtures/foo.bar.baz.json')
}).then((responseJson) => {
expect(responseJson).to.deep.eq({ quux: 'quuz' })

return p
})
.wait('@get').its('response.body').should('deep.eq', { quux: 'quuz' })
})

it('doesn\'t automatically parse JSON response bodies if content-type is wrong', function () {
const p = Promise.defer()

cy.http('/json.txt', (req) => {
req.reply((res) => {
expect(res.body).to.eq('{ "foo": "bar" }')
p.resolve()
})
}).as('get')
.then(() => {
return $.get('/fixtures/json.txt')
}).then((responseText) => {
expect(responseText).to.deep.eq('{ "foo": "bar" }')

return p
})
.wait('@get').its('response.body').should('deep.eq', '{ "foo": "bar" }')
})

it('sets body to string if JSON is malformed', function () {
const p = Promise.defer()

cy.http('/invalid.json', (req) => {
req.reply((res) => {
expect(res.headers['content-type']).to.match(/^application\/json/)
expect(res.body).to.eq('{ foo:::: }')
p.resolve()
})
}).as('get')
.then(() => {
return $.get('/fixtures/invalid.json').catch(() => p)
})
.wait('@get').its('response.body').should('deep.eq', '{ foo:::: }')
})
})

context('with StaticResponse', function () {
it('res.send(body)', function () {
cy.http('/custom-headers', function (req) {
Expand Down Expand Up @@ -1786,7 +1906,7 @@ describe('network stubbing', { retries: 2 }, function () {

expect(log.get('alias')).to.eq('getFoo')

expect(JSON.parse(res.response.body as string)).to.deep.eq({
expect(res.response.body).to.deep.eq({
some: 'json',
foo: {
bar: 'baz',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
SERIALIZABLE_REQ_PROPS,
NetEventFrames,
} from '../types'
import { parseJsonBody } from './utils'
import {
validateStaticResponse,
getBackendStaticResponse,
Expand Down Expand Up @@ -49,6 +50,8 @@ export const onRequestReceived: HandlerFn<NetEventFrames.HttpRequestReceived> =
const route = getRoute(frame.routeHandlerId)
const { req, requestId, routeHandlerId } = frame

parseJsonBody(req)

const request: Partial<Request> = {
id: requestId,
request: req,
Expand Down Expand Up @@ -139,6 +142,10 @@ export const onRequestReceived: HandlerFn<NetEventFrames.HttpRequestReceived> =

_.merge(request.request, continueFrame.req)

if (_.isObject(continueFrame.req!.body)) {
continueFrame.req!.body = JSON.stringify(continueFrame.req!.body)
}

emitNetEvent('http:request:continue', continueFrame)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ import {
import $errUtils from '../../../cypress/error_utils'
import { HandlerFn } from './'
import Bluebird from 'bluebird'
import { parseJsonBody } from './utils'

export const onResponseReceived: HandlerFn<NetEventFrames.HttpResponseReceived> = (Cypress, frame, { getRoute, getRequest, emitNetEvent }) => {
const { res, requestId, routeHandlerId } = frame
const request = getRequest(frame.routeHandlerId, frame.requestId)

parseJsonBody(res)

let sendCalled = false
let resolved = false

Expand Down Expand Up @@ -49,11 +52,15 @@ export const onResponseReceived: HandlerFn<NetEventFrames.HttpResponseReceived>
}

if (request) {
request.response = continueFrame.res
request.response = _.clone(continueFrame.res)
request.state = 'ResponseIntercepted'
request.log.fireChangeEvent()
}

if (_.isObject(continueFrame.res!.body)) {
continueFrame.res!.body = JSON.stringify(continueFrame.res!.body)
}

emitNetEvent('http:response:continue', continueFrame)
}

Expand Down
20 changes: 20 additions & 0 deletions packages/driver/src/cy/net-stubbing/events/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { find } from 'lodash'
import { CyHttpMessages } from '@packages/net-stubbing/lib/types'

export function hasJsonContentType (headers: { [k: string]: string }) {
const contentType = find(headers, (v, k) => /^content-type$/i.test(k))

return contentType && /^application\/json/i.test(contentType)
}

export function parseJsonBody (message: CyHttpMessages.BaseMessage) {
if (!hasJsonContentType(message.headers)) {
return
}

try {
message.body = JSON.parse(message.body)
} catch (e) {
// invalid JSON
}
}
2 changes: 1 addition & 1 deletion packages/net-stubbing/lib/external-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ type Method =
| 'unsubscribe'

export namespace CyHttpMessages {
interface BaseMessage {
export interface BaseMessage {
body?: any
headers: { [key: string]: string }
url: string
Expand Down

4 comments on commit 6ee7a9c

@cypress-bot
Copy link
Contributor

@cypress-bot cypress-bot bot commented on 6ee7a9c Nov 23, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Circle has built the linux x64 version of the Test Runner.

Learn more about this pre-release platform-specific build at https://on.cypress.io/installing-cypress#Install-pre-release-version.

Run this command to install the pre-release locally:

npm install https://cdn.cypress.io/beta/npm/6.0.0/circle-develop-6ee7a9c27e9ea8b7dceee6bae140ce86d816a5e1/cypress.tgz

@cypress-bot
Copy link
Contributor

@cypress-bot cypress-bot bot commented on 6ee7a9c Nov 23, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AppVeyor has built the win32 x64 version of the Test Runner.

Learn more about this pre-release platform-specific build at https://on.cypress.io/installing-cypress#Install-pre-release-version.

Run this command to install the pre-release locally:

npm install https://cdn.cypress.io/beta/npm/6.0.0/appveyor-develop-6ee7a9c27e9ea8b7dceee6bae140ce86d816a5e1/cypress.tgz

@cypress-bot
Copy link
Contributor

@cypress-bot cypress-bot bot commented on 6ee7a9c Nov 23, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AppVeyor has built the win32 ia32 version of the Test Runner.

Learn more about this pre-release platform-specific build at https://on.cypress.io/installing-cypress#Install-pre-release-version.

Run this command to install the pre-release locally:

npm install https://cdn.cypress.io/beta/npm/6.0.0/appveyor-develop-6ee7a9c27e9ea8b7dceee6bae140ce86d816a5e1/cypress.tgz

@cypress-bot
Copy link
Contributor

@cypress-bot cypress-bot bot commented on 6ee7a9c Nov 23, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Circle has built the darwin x64 version of the Test Runner.

Learn more about this pre-release platform-specific build at https://on.cypress.io/installing-cypress#Install-pre-release-version.

Run this command to install the pre-release locally:

npm install https://cdn.cypress.io/beta/npm/6.0.0/circle-develop-6ee7a9c27e9ea8b7dceee6bae140ce86d816a5e1/cypress.tgz

Please sign in to comment.