Test fail when using Cypress session - javascript

I have the following code:
export function backofficeAuthenticate(username, password) {
cy.session(['Login'], () => {
cy.request({
log: false,
method: 'POST',
url: getBackUrl('/login.htm'),
qs: {
redir: getBackUrl('/back'),
},
followRedirect: false,
body: {
'Login_login-email': username,
'Login_login-password': password,
'action[Login_login:login]': 'login',
},
});
});}
And I am calling a function to login like that:
export function loginWithAdmin() {
backofficeAuthenticate(Cypress.env('WEB_LOGIN_USERNAME'), Cypress.env('WEB_LOGIN_PASSWORD'));
}
My code in the test is:
import { loginWithAdmin, httpAuthentication } from '../../cypress/support/bestreviews.js';
describe('Dashboard types quick smoke', () => {
const endpoints = [
'/dashboard',
'/dashboard/articles',
'/dashboard/archive',
'/dashboard/syndicated',
'/dashboard/tribunearticles',
'/dashboard/giftguides',
'/dashboard/blogposts',
];
endpoints.forEach((endpoint) => {
it(endpoint, () => {
cy.visitBackOffice(endpoint);
httpAuthentication();
loginWithAdmin();
cy.checkErrorFree();
cy.get('.dashboard-entries').should('exist');
cy.get('[data-content="topic-info"]').should('exist');
});
});
});
After I execute the code, I always got an error:
(uncaught exception) TypeError: Cannot read properties of null
(reading 'style') TypeError The following error originated from your
application code, not from Cypress.
Cannot read properties of null (reading 'style')
When Cypress detects uncaught errors originating from your application
it will automatically fail the current test.
This behavior is configurable, and you can choose to turn this off by
listening to the uncaught:exception event.Learn more
Does anyone know what I am missing? I think the problem is with cypress session, but not sure how to proceed...

To make sure that cypress catches exceptions generated from your application you can add this in cypress/support/e2e.js
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
})
Note: One thing to note is that if you add this, cypress will not catch exceptions generated from your application, which is not a good practice, because you want your tests to catch exceptions.

Related

Posting result data to a website (like API or a telegram bot) after a test on Cypress

I've finished writing my first Cypress test. Everything is good except I'm struggling to post the result data to a website. Because I want to send the result data and also if any errors occurs the result screenshot to our coworker telegram group.
For the last two days I've tried everything and couldn't find any solution.
I've tried those in my test script (cypress/integration/test.js);
Cypress.on('test:after:run', (test, runnable) => {
console.log('test,runnable', test, runnable)
const details = {
projectKey: Cypress.env('zephyr-project-key'),
testName: test.invocationDetails.relativeFile,
status: test.status,
error: runnable.err.message,
retries: runnable.retries.length,
duration: test.wallClockDuration,
startTime: test.wallClockStartedAt
}
cy.request('POST', 'http://mywebsite.com/notify.php', { body: details })
fetch('http://mywebsite.com/notify.php')
})
Also this didn't work (cypress/plugins/index.js);
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on('after:run', (results) => {
if (results) {
// results will be undefined in interactive mode
console.log(results.totalPassed, 'out of', results.totalTests, 'passed')
fetch('http://mywebsite.com/notify.php');
}
})
}
Edit: This is day 3 and I still couldn't solve this. What I've seen from Cypress help page is that cy.task() calls do not fire in 'test:after:run' event block;
https://github.com/cypress-io/cypress/issues/4823
I've seen some telegram groups who can do what I'm trying to do. All I need is to be able to get the results and post it to my website.
The third parameter to cy.request() is body, you don't have to wrap it.
Cypress.on('test:after:run', (test, runnable) => {
const details = {
projectKey: Cypress.env('zephyr-project-key'),
testName: test.invocationDetails.relativeFile,
status: test.status,
error: runnable.err?.message, // need err?.message if there is no error
retries: runnable.retries.length,
duration: test.wallClockDuration,
startTime: test.wallClockStartedAt
}
cy.request('POST', 'http://mywebsite.com/notify.php', details) // don't wrap details
.then(res => expect(res.status).to.eq(201)) // confirm result
})

cypress cy.route not behaving consistently

I am trying to stub out a route using cypress 5.2. I have a simple function to do that:
function mockAlertsResponses(){
cy.route({
method: "GET",
url: "/api/polling/alerts/statistics*",
response: {
total: 2,
...
}
});
}
In one set of tests, this works just fine:
describe("admin and read only permissions", () => {
it ("all action bar items are enabled with admin permissions", () => {
cy.login("user", "password");
mockAlertsResponses();
// Click alert to enable all buttons
cy.get("#1-checkbox").click()
cy.get("#mark-alert-button").should("be.enabled");
cy.get("#delete-alert-button").should("be.enabled");
});
// ... a few more similar tests
});
However, in another set of tests, I use the same function:
it("Logs in and out", () => {
cy.login("username", "password");
mockAlertsResponses()
cy.get("#vine-appbar").should("be.visible");
cy.get("#info-button").click();
cy.get("#info-menu-logout").click();
cy.get("#login-button");
cy.get("#vine-appbar").should("not.be.visible");
});
In this second set of tests, the routes are not stubbing properly, leading to errors and test failures. Here, you can see the route is not stubbed, but rather throws a 500 error:
I'm not sure what could be interfering here. I'm a bit new to cypress and I'm not even sure where to begin debugging this. Might the cy.server calls be interfering? Please let me know what more information we'd need to figure out why one set of stubs works and another doesn't.
If you're wondering, the login function has a call to cy.server and has its own cy.route as well:
Cypress.Commands.add("login", (username, password, admin = true) => {
const response = admin ? <jwt1> : <jwt2>
cy.server();
cy.route({
method: "POST",
url: "/api/login",
response
});
cy.visit("/logout");
cy.visit("/");
cy.wait(100);
cy.get("#login-error").should("not.be.visible");
cy.get("#login-username").type(username);
cy.get("#login-password").type(password);
cy.get("#login-button").click();
});

Chrome proxy api - Uncaught TypeError: Invalid invocation

I want to use the chrome proxy API. I have this code in my background script but it will not work
const proxyData = []
const fetchProxyData = () => {
axios({
method: "GET",
baseURL: "https://api.getproxylist.com/proxy",
params: {
protocol: "http",
allowsPost: 1,
allowsHttps: 1,
anonimity: "high anonymity"
}
}).then( (response) => {
console.log(response.data)
proxyData.push(response.data)
})
}
fetchProxyData();
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
host: proxyData.ip,
port: proxyData.port
}
}
}
chrome.proxy.settings.set({
value: config,
scope: "regular"
}, () => {
console.log(`proxy configured with data: ${proxyData}`)
})
I get this error in background page console: background.js:55 Uncaught TypeError: Invalid invocation
I've tried with the example provided with the proxy api documentation and the error will not occur. Maybe it's caused by the config object? To set the proxy as you can see in the code, I'm using an ajax call, maybe is this the problem?
is there any fix?
I have also faced the same problem when I find the solution, it was silly mistake.
I had passed string value to port.
Please make sure you are passing integer value to port
Close. Couple things.
One, you need to fetch your data before calling Chrome's proxy API. And two, your getting the properties for your config from the proxyData array, not the JSON object from your axios call.
You need to do something like this:
const proxyData = [];
const fetchProxyData = () => {
axios({
method: "GET",
baseURL: "https://api.getproxylist.com/proxy",
params: {
protocol: "http",
allowsPost: 1,
allowsHttps: 1,
anonimity: "high anonymity"
}
}).then((response) => {
const {data} = response;
proxyData.push(data);
const config = {
mode: "fixed_servers",
rules: {
singleProxy: {
host: data.ip,
port: data.port
}
}
};
chrome.proxy.settings.set({
value: config,
scope: "regular"
}, () => {
console.log(`proxy configured with data: ${data}`)
});
})
};
fetchProxyData();
What's happening with your code...The properties host and port in singleProxy (in config) are being assigned undefined because those properties don't exist in the array proxyData. They exist in the object returned from your axios call (above, data).
The undefined keys caused Chrome to throw an Invalid Invocation error.
For anyone else getting the Invalid Invocation issue, it seems to me the problem usually lies within the config your passing into Chrome. In particular the types of each key.
In my case, I was passing in the port as a string when it needed to be a number.

Validating the cookie cypress throws 'TypeError: cy.chain is not a function

I am validating the cookie in my below 'login' Cypress test, but cypress throws following error :
TypeError: cy.chain is not a function
Clearly imported the following under '../support/index.js' Can someone please advise why the error is throwing
import './commands'
cypress test:
describe("Login test validate cookie", () => {
it.only('Verify the cookies test for login', function() {
cy
.login(Cypress.env('email'), Cypress.env('password'))
cy
.getCookie('csrftoken')
.then((csrftoken) => {
console.log(csrftoken)
})
})
Following is my 'login' method/function ../support/commands.js
Cypress.Commands.add('login', (email, password) => {
return cy.chain().request({
method: 'POST',
form: true,
url: '${cypress.env("test_server")}',
body: '{"email", "password"}',
})
});
The below details are provided in 'cypress.env.json' file
{
"email": "test#soccer.nl",
"password": "test1234"
}
The error is correct; cy.chain() is indeed not a function. However, there are a number of issues in your command:
Unless you plan to chain off this command, you don't need to return anything. It certainly doesn't hurt anything though.
As mentioned previously, .chain() is unnecessary.
Your url field needs to use backticks (``) for the ${...} to work.
Your body field is going to contain "email" and "password", instead of your actual email and password.
It's possible there are other issues, but these are the ones I can see.
Here's what your command would look like without those issues:
Cypress.Commands.add('login', (email, password) => {
cy.request({
method: 'POST',
form: true,
url: `${cypress.env("test_server")}`,
body: `{"${email}", "${password}"}`,
});
});

Internal Server Error when using Meteor.loginWithFacebook

Using the service-configuration and accounts-facebook packages, after clicking on the facebook button and logging in from the Facebook authorization window that pops up, we're getting an Internal server error when performing a Meteor.loginWithFacebook.
This was tested on a very basic example, what is causing this error?
Template.login.events({
'click .btn-facebook': function (ev) {
Meteor.loginWithFacebook({}, function(error) {
if(error) {
throw new Meteor.Error('Facebook login failed: ', error);
}
})
}
});
/server/lib/config/social.js
Meteor.startup(function() {
ServiceConfiguration.configurations.update(
{ service: "facebook" },
{ $set: {
appId: "xxx",
secret: "xxx"
}
},
{ upsert: true }
);
})
Error (server side)
Exception while invoking method 'login' undefined
Error (client side)
Error: Internal server error [500]
at _.extend._livedata_result (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:4964:23)
at onMessage (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:3725:12)
at http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:2717:11
at Array.forEach (native)
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?0a80a8623e1b40b5df5a05582f288ddd586eaa18:156:11)
at _.extend._launchConnection.self.socket.onmessage (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:2716:11)
at REventTarget.dispatchEvent (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:156:22)
at SockJS._dispatchMessage (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:1141:10)
at SockJS._didMessage (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:1199:18)
at WebSocket.SockJS.websocket.that.ws.onmessage (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:1346:17)
I had the same issue, and solved it like this :
After checking that you have configured your schema as described here :
Schema.User = new SimpleSchema({
_id: {
type: String
}
...
});
You should add the second part into an Accounts.onCreateUser like this, into server/accounts.js for example :
Accounts.onCreateUser(function (options, user) {
if (user.services.facebook) {
user.emails = [{
address: user.services.facebook.email,
verified: true
}];
}
return user;
});
It will append the facebook email to the newly created account. The error should disapear.

Categories