New window not opening in cypress - cypress

I want to open a new window and create one fake email address in that window. after that I want to close that window.
Here is what I have tried.
it.only('Sign up', function () {
cy.visit('/')
cy.xpath('//button[text()=" Sign Up with Email"]').click()
cy.get('#email').type(email.toLocaleLowerCase())
cy.fixture("data.json").then(profile => {
profile.email = email
cy.writeFile("cypress/fixtures/data.json", profile);
cy.window().then((win) => {
cy.stub(win, 'open').as('redirect');
})
cy.get('.ant-btn').click()
cy.wait(1000)
cy.get('#redirect').should('be.calledWith')
});
});
And here is my test runner image. the window is not called.
And if the window is open, how to use the command in that.

Related

How to test an Alert with Cypress

I'm testing a data form using Cypress, but am stuck on a step that displays an alert on the page.
This is the test, but it's not working.
describe('Alert is displayed with warning text', () => {
it('Assert that the alert is displayed after entering data', () => {
cy.visit('/')
cy.get('input').type('some data').blur()
cy.on ('window:alert', (text) => {
cy.wrap(text).should('eq', 'alert text')
})
})
})
How do I test this alert that pops up on the page?
The code cy.on('window:alert') is an event listener.
Instead of adding a callback as you would do for other commands, you can add a stub and check the stub function has been called plus the text it is called with.
Also because it's a listener, you must set it up before the event that triggers the event.
describe('Alert is displayed with warning text', () => {
it('Assert that the alert is displayed after entering data', () => {
cy.visit('/')
const stub = cy.stub()
cy.on ('window:alert', stub)
cy.get('input').type('some data').blur()
// wait for the event to be handled
cy.then(() => {
expect(stub.getCall(0)).to.be.calledWith('alert text')
})
})
})
You can modify your code to use expect() instead of should().
The problem is Cypress does not like commands inside event listeners.
You must use a done() callback to avoid a false positive when the alert is not fired.
describe('Alert is displayed with warning text', () => {
it('Assert that the alert is displayed after entering data', (done) => {
cy.visit('/')
cy.on ('window:alert', (text) => {
expect(text).to.eq('alert text')
done() // waiting for event, fails on timeout
)
cy.get('input').type('some data').blur()
})
})

Cypress.Cookies.preserveOnce('session_id') isn't working when called in afterEach hook

I'm working with cypress tests and I want to avoid having to log in before each test. so, I wanted to preserve the cookies in each test file.
The log statement in the afterEach hook is triggered, however cookies are cleared in the second testcase.
describe('Users Page Scenarios', () => {
before(() => {
myApp.pages.Login.navigate();
myApp.pages.Login.login(
credentials.globalAdmin.email,
credentials.globalAdmin.password
);
});
beforeEach('navigate to users page before each test', () => {
myApp.sharedComponents.Header.navigateToUsers();
});
afterEach(() => {
Cypress.Cookies.preserveOnce('session_id');
cy.log('test');
});
describe('Users List', () => {
it('Should redirect the user to users page after clicking on users in the navigation header', () => {
cy.url().should('eq', `${Cypress.config().baseUrl}/user`);
});
})
describe('New User Creation', () => {
it('Should open new user modal after clicking on invite administrator', () => {
myApp.pages.Users.UsersList.inviteAdministrator();
cy.url().should('eq', `${Cypress.config().baseUrl}/user/new`);
});
it('Should create a new user successfully', () => {
myApp.pages.Users.UsersList.inviteAdministrator();
myApp.pages.Users.UsersInfo.createNewUser(user.generateUser());
})
});
The docs indicate that Cypress.Cookies.preserveOnce('session_id') is used in beforeEach().
Looks like after is too late.
describe('Dashboard', () => {
before(() => {
// log in only once before any of the tests run.
// your app will likely set some sort of session cookie.
// you'll need to know the name of the cookie(s), which you can find
// in your Resources -> Cookies panel in the Chrome Dev Tools.
cy.login()
})
beforeEach(() => {
// before each test, we can automatically preserve the
// 'session_id' and 'remember_token' cookies. this means they
// will not be cleared before the NEXT test starts.
//
// the name of your cookies will likely be different
// this is an example
Cypress.Cookies.preserveOnce('session_id', 'remember_token')
})
If you have localStorage or sessionStorage to preserve, or you have not identified all cookies correctly, try with cy.session()
beforeEach(() => { // must be beforeEach()
cy.session('mySession', () => { // preserves localStorage, sessionStorage, cookies
myApp.pages.Login.navigate();
myApp.pages.Login.login(...); // only called once (despite beforeEach())
})
})

Teams auth popup wont close or redirect after completing sign in (React)

I have a React app (with React Router) running inside of a MS Teams tab, and I'm trying to have the user sign-in with azure ad redirect. A popup opens when they click the sign in button, but when they finish the auth procedure, the redirect happens inside the popup instead of closing and redirecting back to the tab.
When the sign-in button is clicked this runs inside of the SignIn component:
function loginTeams() {
microsoftTeams.authentication.authenticate({
url: window.location.origin + "/teams-auth",
width: 600,
height: 535,
successCallback: function (result) {
console.log('success')
},
failureCallback: function (reason) {
console.log('failed')
}
});
}
Then it redirects to the TeamsAuth component which opens the popup:
useEffect(() => {
microsoftTeams.initialize();
microsoftTeams.getContext(function (context) {
let authorizeEndpoint = buildAzureSSOLink(context);
window.location.assign(authorizeEndpoint);
});
}, []);
The redirect uri is set to /teams-auth-end which redirects to the TeamsAuthEnd component,
which calls the notify success method:
const queryParams = parseQueryParams(location);
useEffect(() => {
microsoftTeams.initialize();
microsoftTeams.authentication.notifySuccess({
accessToken: queryParams.access_token
})
}, []);
I suspect the problem has to do with calling microsoftTeams.initialize() in more than one spot, but removing them stops the popup from opening. Any ideas on what I'm doing wrong?

How can I close the browser after a mocha test?

I am new to WebdriverIO and Mocha and I wrote 2 tests in order to check our web app.
I want to close the browser and sign-in again, after I run the first test.
When I used browser.close(), I got an error the browser.close() is not a function and basically the second test runs right after the first test with the browser being open.
Is there a way to close to browser after a test in Mocha?
describe('Verify that a signed-in user can get to the page', () => {
it('Title assertion ', () => {
const viUrl = 'https://buyermanage.com/bmgt/lock?useMock=pre.json';
signInPage.signIn('rich221', 'password', viUrl);
assert.equal(preApp.getTitle(), 'Pre-App', 'Title Mismatch');
});
});
describe("Verify that a not signed-in user can't get to the page and is redirected to login page", () => {
it('Title assertion ', () => {
const viUrl = 'https://buyermanage.com/bmgt/lock?useMock=pre.json';
assert.equal(preApp.getTitle(), 'Pre-App', 'Title Mismatch');
});
});
Try using browser.reloadSession():
after(() => {
// Start a new session for every 'locale' (wipe browser cache):
browser.reloadSession();
});
In your particular example, you'd need to use it in the afterEach() hook, and wrap the describes, respectively the it statements (depending on your test-suite requirements) inside a parent describe block:
describe('The world is your oister', () => {
describe('Verify that a signed-in user can get to the page', () => {
it('Title assertion ', () => {
// bla bla bla
});
});
describe("Verify that a not signed-in user can't get to the page and is redirected to login page", () => {
it('Title assertion ', () => {
// bla bla bla
});
});
afterEach(() => {
browser.reloadSession();
});
});

Protractor expect direct to a page with specific url

I have a button on my page, I want to write an e2e test using Protractor. What I want to implement is that when clicking the button, page change to http://localhost:8100/#/booking. How can I implement that?
describe('booking function', function() {
it('should go to booking page', function() {
broswer.get(localHostCruises);
element(by.css('.button.button-stable.button-block')).click();
//sudo code
expect(page change to "http://localhost:8100/#/book" );
})
})
you need to use the browser.getCurrentUrl() method, so something like this:
element(by.css('.button.button-stable.button-block')).click().then(function () {
expect(browser.getCurrentUrl()).toEqual("http://localhost:8100/#/book");
})
You can achieve this with below code.
let targetLocation = 'your/target/location';
browser.get('localHostCruises'); // Login page.
element(by.css('.button.button-stable.button-block')).click(); // click on button.
browser.setLocation(targetLocation);
// If Login takes some time, so wait until it's done.
browser.wait(() => {
return browser.getCurrentUrl().then((url) => {
let isMatch = url.match(targetLocation);
if (isMatch) {
page = new Page; // I assume you writing test cases in page object.
} else {
browser.setLocation(targetLocation);
}
return isMatch;
});
}, 2000, 'Should throw an error message.');

Resources