I try to use Cypress.io cy.route() to manage the behaviour of network requests. A stub was wrtitten to replace the network behaviour of the application to test the UI.
The expected results is for the backend to return a string-typed response in JSON format. Quotes or double quotes should not appear outside of the bracket.
An example of the expected result:
{"mockdata":"mock"}
However, my App kept returning object-typed response during the test, such as
{mockdata:"mock"}
How to make Mock API to return string-typed response? Thank you.
Attached below are my test codes:
context('mock API', function () {
before(function () {
cy.server()
cy.route({
method: 'POST',
url: '/category/menu',
response: '{"mockdata":"mock"}'
}).as('rootBlock')
}
it('use mock API', function () {
cy.visit('/')
cy.wait('@rootBlock')
})
}
And the sample code of my APP using JQuery:
$.ajax({
url: '/category/menu',
type: 'POST',
success: function (json) {
console.log(typeof json)
// Expect String to be returned
// but it always return as Object during a cypress test
var jsonData = $.parseJSON(json).mockdata
// throwing errors...
}
});
And my system is: Win7 x64
node.js: v10.14.1
Cypress.io: v3.4.1
Your mock tries to automatically cast your response into a JSON object (has it should be).
If you want to return a string, you should stringify your object :
response: JSON.stringify({"mockdata":"mock"})
should works.
Also you may add an header property with :
header: {
'Content-Type': 'text/html'
},
but it should not be mandatory in your case
You can also check the documentation there : https://docs.cypress.io/api/commands/route.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.