I looking for a way to intercept all request in cypress.
I'm thinking about a thing like that:
beforeEach(() => {
cy.intercept({method: 'GET', path: '*'}).as('get')
cy.intercept({method: 'POST', path: '*'}).as('post')
})
then:
afterEcah(() => {
cy.wait('#get').its('response.statusCode').should('be.oneOf', [200, 304])
cy.wait('#post').its('response.statusCode').should('be.oneOf', [200, 304, 201])
})
My problem is sometime in my test i don't have a get or a post request, so my test fail.
Maybe i need a condition is my afterEach() but i can' t figure it out.
Or perhaps the problem is using afterEach() for this purpose.
Any help will be welcome
For all requests, you can put your code into cypress/support/e2e.js file:
beforeEach(() => {
cy.intercept({method: 'GET', path: '*'}).as('get')
cy.intercept({method: 'POST', path: '*'}).as('post')
})
Related
I would like to ask for your help regarding the authentication token to be used in other API calls.
Below are the scripts of the command and test case:
//command.js
import "cypress-localstorage-commands";
Cypress.Commands.add('login', () => {
cy.request({
method: 'POST',
url: Cypress.env('api_auth'),
body: {
email: Cypress.env('email'),
password: Cypress.env('password'),
}
})
.its('body')
.then(body => {
cy.window().then(win => win.localStorage.setItem('jwt', body.token))
})
//test case
describe('GET Data', ()=> {
before(() => {
cy.login();
cy.saveLocalStorage();
});
beforeEach(() => {
cy.restoreLocalStorage();
});
it('GET - View All Data', () =>{
cy.request({
method : 'GET',
url : Cypress.env('api_data'),
}).then((res) =>{
expect(res.status).equal(200)
})
})
In my approach i have the same command, but instead of storing the token in the local storage, I'm adding it to the cypress.env file in the object of the admin, because i have several admins so my object file goes like so
{
admins:
admin1:{
"username":"admin1",
"password": "123456",
"token":""
},
admin2:{
"username":"admin1",
"password": "123456",
"token":""
}
}
This way you can store several admins/user tokens and just attach as:
Cypress.env.admins.admin1.token
or
Cypress.env.admins.admin2.token
I think this approach is simpler and in about 300 tests i've seen no problems regarding speed of the test execution or anything other
I am new in Cypress,
I wanted to create my first code for API in cypress.
Here is the details
POST
https://www.mywebsite.com/myproject/get-customer-login-url
HEADER
------
KEY: token
VALUE: HKt7854UHTFGR78#78
DESCRIPTION:
KEY: Content-Type
VALUE: application/json
DESCRIPTION:
BODY
-----
RAW:
{
"customerid": "54607"
}
Using above parameters, I got below result and status in Postman.
RESULT:
"{\"url\":\"default.aspx?rootid=843&companyId=54607&eccuserid=0&isloginspecialrole=False&userid=e91zNO%2bBBCI%3d&t=view\",\"code\":\"1\"}"
STATUS"
200 OK
I need to made script for cypress using these POST URL and parameters/key.
And want response like
https://www.mywebsite.com/myproject/default.aspx?rootid=843&companyId=54607&eccuserid=0&isloginspecialrole=False&userid=e91zNO%2bBBCI%3d&t=view
can anyone help me out to my cypress script?.
Here's an example, you might have to adjust it. This example just validates that status of the response is 200 but you can validate response contents as well. Refer cypress docs for details:
describe('Test the api', function() {
it ('status should be 200', () => {
cy.request({
method: 'POST',
url: 'your-url',
followRedirect: false,
headers: {
'token': 'HKt7854UHTFGR78#78',
'Content-Type': 'application/json',
},
body: {"customerid": "54607"},
})
.then((response) => {
expect(response.status).to.equal(200)
})
})
})
I have a problem with the right in strapi.
I create user with the role Authenticated and try modified the data with axios.
But it is impossible has modified because return forbidden. I look if the user has right, Update is check in role authenticated.
If i check update in role public, my modification with axios is ok. Why ? I don't undestand the problem.
My code for send
.put(
`https://localhost:4000/users/${this.data.id}`,
{
headers: {
Authorization: `Bearer ${token}`
},
Nom: 'JEAN'
}
)
.then((res) => {
// Handle success.
console.log(res)
})
.catch((error) => {
// Handle error.
console.error('An error occurred:', error)
})```
Thank you
I'm not sure the axios request has the right format.
According to this documentation - https://github.com/axios/axios#axiosconfig
This probably should look like this:
axios({
method: 'put',
url: `https://localhost:4000/users/${this.data.id}`,
data: {
username: 'JEAN'
},
headers: {
Authorization: `Bearer ${token}`
}
});
I have encountered server.inject in test examples, but not in production code example.
I have a route that needs to execute something that is handled by another route, so I need to make an internal call.
handler: (req, res) => {
const OPTIONS = {
method: 'POST',
path: '/path'
payload: {PAYLOAD_HERE}
}
server.inject(OPTIONS, (err, response) => {
res(response)
});
}
is this okay?
Yes. I've done exactly that in a large scale production system.
I have a Jasmine test spec test_spec.js like this:
describe('my tests', () => {
it('POST should return 201 created', () => {
var req = {
method: 'POST',
url: '/api/v1.0/message',
payload: JSON.stringify({name: 'Ethan'})
};
server.inject(req, res => {
expect(res.statusCode).to.equal(201);
});
});
});
The route for the API call looks like this:
var routes = [{
path: '/api/v1.0/message',
method: 'POST',
handler: function(request, reply) {
reply('Success').created();
}
}];
exports.register = function(server, options, next) {
server.route(routes);
next();
}
When I run the tests, though, this particular test's expect() function doesn't get called because the server.inject() method doesn't call the response callback. In fact, not even the route handler method gets called (I checked with console.log statements). However, when I change the request method and the route from POST to GET, it works and the test calls the expect() method as expected. The test just doesn't work with POST requests. Am I doing it wrong?
Turns out that the problem was in the test call describe() snippet posted in my question. I neglected to call the done() function inside the server.inject() call. Once I added that, the POST test started getting called:
describe('my tests', () => {
it('POST should return 201 created', (done) => {
var req = {
method: 'POST',
url: '/api/v1.0/message',
payload: JSON.stringify({name: 'Ethan'})
};
server.inject(req, res => {
expect(res.statusCode).toEqual(201);
done();
});
});
});
The need to call the done() callback wasn't obvious to me from the Jasmine documentation. The call is necessary in order to postpone the spec completion until done() is called (meaning payload is posted).