Nightwatch.js - How to do assertion on new browser tab - selenium

I have to test one scenario. User types desired URL to text which is linked with button. When user clicks this button, user will be directed to typed URL.
When I do assertion for new tab (Google), output is always like "localhost:8080" which is my previous tab (currentPage).
I think I should set new tab to "this" but, I could not figure it out. If you can help me, I will be appreciated.
linkTest.spec.js
module.exports = {
tags: ['component', 'linkTest'],
before: function(client, done) {
this.currentPage = client.maximizeWindow().page.linkTestPage();
this.currentPage
.navigate(client.globals.devUrl)
.waitForElementVisible('body', 60000)
.customPerform(function() {
done();
});
},
'CASE ID - Case Name'() {
let googleUrl = 'https://www.google.com/';
this.currentPage
.checkInitialElements()
.setExternalUrlText(googleUrl)
.clickLinkLabel();
// Handle with new tab
this.client.windowHandles(function(result) {
let googleTab = result.value[1]; // New Google tab index
this.switchWindow(googleTab) // Switch to Google tab
.assert.urlContains('Google'); // Verify new tab is Google
});
},
after: function(client, done) {
client.end().customPerform(done);
},
};
customPerform.js
exports.command = function(fn, callback) {
this.perform(fn);
if (typeof callback === 'function') {
callback.call(self);
}
return this; // allows the command to be chained.
};

Not sure if you've already figured out how to do this or not, but the way that I was able to is to throw the assertions for the new page into a callback function for the switchWindow function. So in your example,
// Handle with new tab
this.client.windowHandles(function(result) {
let googleTab = result.value[1]; // New Google tab index
// Switch to Google tab
this.switchWindow(googleTab, function() {
this.assert.urlContains('Google'); // Verify new tab is Google
});
});

Related

Web app that runs in Microsoft Teams (personal tab) doesn't always work on Desktop version

I have a Web app built in Vuejs and has SSO authentification using microsoftTeams.authentication.getAuthToken when running in Teams, or microsoftAuthLib when running in the browser.
Inside the company's network or when connected to the VPN everything works absolutely fine.
We recently opened it outside of the VPN and we created a public certificate for it. So when I disconnect the VPN, it works:
In any browser (outside of Teams).
Teams browser version.
Teams on Android/iPhone.
But it doesn't work on Teams Windows Desktop version, it fails with the following error:
Refused to display
'https://login.microsoftonline.com/.../oauth2/authorize?...' in a
frame because it set 'X-Frame-Options' to 'deny'.
Anybody has an idea what could be the issue? And why would it work on the company's VPN but not outside?And only on specific cases? I am lost, any help would be appreciated.
Thank you
*** EDIT / ADDED SSO REDIRECT CODE ***
import * as microsoftTeams from "#microsoft/teams-js";
import * as microsoftAuthLib from "msal";
import settings from './settings.js';
var msalConfig = {
auth: {
clientId: settings.sso.id,
authority: settings.sso.authority
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var requestObj = {
scopes: settings.sso.scopes
};
var myMSALObj = new microsoftAuthLib.UserAgentApplication(msalConfig);
myMSALObj.handleRedirectCallback(authRedirectCallBack);
function authRedirectCallBack(error, response) {
if (error) {
console.log(error);
} else {
console.log("token type is:" + response.tokenType);
}
}
function loginRedirect(requestObj) {
let account = myMSALObj.getAccount();
if (!account) {
myMSALObj.loginRedirect(requestObj);
return false;
} else {
return true;
}
}
function acquireMsalToken() {
return new Promise(function (resolve) {
resolve(myMSALObj.acquireTokenSilent(requestObj).then(token => {
return token.accessToken;
}).catch(error => {
acquireMsalTokenRedirect(error);
}));
})
}
function acquireTeamsToken() {
return new Promise((resolve, reject) => {
microsoftTeams.authentication.getAuthToken({
successCallback: (result) => {
resolve(result);
},
failureCallback: (error) => {
reject(error);
}
});
});
}
function acquireMsalTokenRedirect(error) {
if (error.errorCode === "consent_required" ||
error.errorCode === "interaction_required" ||
error.errorCode === "login_required") {
myMSALObj.acquireTokenRedirect(requestObj);
}
}
var msal = {
autoSignIn: function () {
return loginRedirect(requestObj);
},
acquireToken: async function () {
if (settings.sso.inTeams) {
microsoftTeams.initialize();
microsoftTeams.enterFullscreen();
return acquireTeamsToken();
} else {
let signedIn = msal.autoSignIn();
if (signedIn) {
return acquireMsalToken();
}
}
}
}
export default msal
This error means that you are trying to redirect your tab's iframe to the AAD login flow which in turn is unable to silently generate an auth token for you and is attempting to show an interactive flow (e.g. sign in or consent):
Refused to display
'https://login.microsoftonline.com/.../oauth2/authorize?...' in a
frame because it set 'X-Frame-Options' to 'deny'.
To avoid this issue you need to try and acquire a token silently and if that fails use the microsoftTeams.authentication.authenticate API to open a popup window and conduct the AAD login flow there.
Replacing the acquireTeamsToken() function with the following resolved the issue.
function acquireTeamsToken() {
return new Promise((resolve, reject) => {
microsoftTeams.initialize(() => {
microsoftTeams.authentication.authenticate({
url: window.location.origin + "/ms-teams/auth-start",
width: 600,
height: 535,
successCallback: (result) => {
resolve(result);
},
failureCallback: (error) => {
reject(error);
}
});
});
});
}
I found this documentation very helpful on how to create the Authentication pop up and how to create a Callback window with the Token in it.
You might also want to cache the token and only create a popup when it expires.
This might be because you're using the auth popup option instead of the redirect option in whichever auth library you're using (hopefully MSAL 2.0). Teams is a little different because it's actually launching a popup for you when necessary, so although it sounds a bit strange, you actually want to use the redirect option, inside the popup that is launched. What might help is to look at the new SSO Sample app in the Teams PnP samples.
Go to: %APPDATA%\Microsoft\Teams
Open the file hooks.json (if it's not there, create it)
Add the following to it: {"enableSso": false, "enableSsoMac": false}
That's it, now Teams desktop has the same authentication workflow as the browser version. Have a nice day.

Can't get click_action to work on FCM notifications with web app / PWA

I'm trying to get my "click_action" to take users to specific URLs on notifications that I'm sending to clients, but whatever I do it either does nothing (desktop) or just opens the PWA (android). The messages are coming through fine (checked in Chrome console) but clicking just doesn't seem to work.
I have the following in my service worker, cribbed from various places including other answers provided on this site:
importScripts('https://www.gstatic.com/firebasejs/7.14.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.3/firebase-messaging.js');
// importScripts('/__/firebase/init.js');
/* An empty service worker! */
self.addEventListener('fetch', function(event) {
/* An empty fetch handler! */
});
var firebaseConfig = {
//REDACTED
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
notificationTitle = payload.notification.title;
notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
click_action: payload.notification.click_action
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
self.addEventListener('notificationclick', function(event) {
let url = event.notification.click_action;
// I've also added a data.click_action field in my JSON notification, and have tried using that
// instead, but that didn't work either
console.log('On notification click: ', event.notification.tag);
event.notification.close(); // Android needs explicit close.
event.waitUntil(
clients.matchAll({ includeUncontrolled: true, type: 'window' }).then( windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
self.onnotificationclick = function(event) {
let url = event.notification.click_action;
console.log('On notification click: ', event.notification.tag);
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({ includeUncontrolled: true, type: 'window' }).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == url && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow(url);
}));
};
The notifications come through fine on both android (installed PWA) and chrome, and the message payload in the developer console is well formatted and received fine. In the message I'm sending from the server I have a URL with a custom parameter on the end (e.g. https://[domain]/list.php?userid=123) but, as above, clicking on the notification doesn't do anything on windows/chrome, and on the android it opens the PWA successfully but then doesn't go to the URL in the payload, it just goes to wherever the PWA was when last open. The "userid" changes depending on the message trigger.
Sample JSON of message payload:
{data: {…}, from: "xxx", priority: "high", notification: {…}, collapse_key: "do_not_collapse"}
collapse_key: "do_not_collapse"
data: {gcm.notification.badge: "[logo URL]", click_action: "https://[URL]/list.php?userid=33"}
from: "xxx"
notification:
body: "'5' has just been added"
click_action: "https://[URL]/list.php?userid=33"
icon: "https://[logo URL]"
title: "alert "
I also saw something about "webpush": { "fcm_options": { "link": "https://dummypage.com"}} on https://firebase.google.com/docs/cloud-messaging/js/receive but couldn't figure out if that was relevant or needed also.
Am very surprised just providing a URL in the click_action doesn't seem to just do that action when you click the notificaiton! Is anything needed in the service worker at all?!?!
Could one of the problems be that the PWA doesn't update the SW regularly, and so if my code above should work (a big if!) then i just need to wait for the SW to update on the installed android app? If so, is there a way to speed up its updating?!?
Thanks so much in advance for any assistance. Am tying myself in knots here!
I spent a lot of time looking for a solution for the same problem. Maybe this can help :
if you send notification with firebase messaging, you can use webpush field. firebase messaging client library execute self.registration.showNotification() ... No more need messaging.onBackgroundMessage in your service worker.
// firebabse-coud-function.js
app.messaging().send({
webpush: {
notification: {
title: notification?.title || "Default title",
icon: notification?.icon || "/icon.png",
badge: notification?.icon || "/icon.png",
},
fcmOptions: {
link: `${BASE_URL || ""}${notification?.clickAction || "/"}`,
}
},
data: {
userID: notification.userID,
link: notification?.clickAction || "/",
},
topic
});
Most importantly, in your service worker add a 'notificationclick' event listener before calling firebase.messaging()
so my service worker looks like:
// firebase-messaging-sw.js
// ...
self.addEventListener('notificationclick', function (event) {
console.debug('SW notification click event', event)
const url = event.notification?.data?.FCM_MSG?.data?.link;
// ...
})
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
// received others messages
})
For me, clicking on the event does not go to the correct url. So i add this:
// background client - service worker
const channel = new BroadcastChannel('sw-messages');
self.addEventListener('notificationclick', function (event) {
console.debug('SW notification click event', event)
const url = event.notification?.data?.FCM_MSG?.data?.link;
channel.postMessage({
type: 'notification_clicked',
data: {
title: event.notification.title,
clickAction: url
}
});
})
// foreground client
const channel = new BroadcastChannel('sw-messages');
channel.addEventListener("message", function (event) {
// go the page
})
I hope this helps someone.
This question and other answers seems to be related to the legacy FCM API, not the v1.
In those case, I needed the SW to open any url sent by FCM, which is by default not possible because host differs (see here).
Also, the notification object as changed, and the url for the webpush config is there now: event.notification.data.FCM_MSG.notification.click_action
So adapting others answers to get the correct field and open the url by only editing the firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/8.2.10/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.10/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
...
})
self.addEventListener('notificationclick', function(event) {
event.notification.close();
// fcp_options.link field from the FCM backend service goes there, but as the host differ, it not handled by Firebase JS Client sdk, so custom handling
if (event.notification && event.notification.data && event.notification.data.FCM_MSG && event.notification.data.FCM_MSG.notification) {
const url = event.notification.data.FCM_MSG.notification.click_action;
event.waitUntil(
self.clients.matchAll({type: 'window'}).then( windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (self.clients.openWindow) {
console.log("open window")
return self.clients.openWindow(url);
}
})
)
}
}, false);
const messaging = firebase.messaging();
(register the addEventListener before initializing messaging)
Just add addeventlistner notification click event before calling firebase.messaging()
Everything will work fine.
importScripts('https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js');
self.onnotificationclick = function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/index' && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow('/index');
}));
};
var firebaseConfig = {
apiKey: "xcxcxcxcxcxc",
authDomain: "xcxcxc.firebaseapp.com",
projectId: "fdsfdsdfdf",
storageBucket: "dfsdfs",
messagingSenderId: "sdfsdfsdf",
appId: "sdfsdfsdfsdfsdfsdf"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

FirebaseUI auth redirecting before Firestore document is created

Setup: Vue.js, Vuetify, FirebaseUI, Firestore, Vue-router, Vue CLI
My expectation: Oauth would succeed, set userEmail in localStorage, create a Firestore document in the users collection, then the page would redirect.
Reality: Oath succeeds, userEmail is set in localStorage, page redirects
I have tried using async/await to no avail and returning nothing from signInSuccessWithAuthResult and using signInSuccessUrl for the redirect didn't work either. window.location.href = "/" and location.href.replace("/") also didn't change anything. If I remove the redirect, the document is created which leads me to believe the redirect interrupts the document creation. I am very new to Firebase but I don't see why this isn't working. Any help would be greatly appreciated and if you need more details please comment.
let ui = firebaseui.auth.AuthUI.getInstance();
if (!ui) {
ui = new firebaseui.auth.AuthUI(firebase.auth());
}
let uiConfig = {
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
],
signInFlow: "popup",
callbacks: {
signInSuccessWithAuthResult: function(authResult) {
let email = authResult.user.isAnonymous
? "guest"
: authResult.user.email;
localStorage.setItem("userEmail", email);
if (
authResult.additionalUserInfo.isNewUser &&
!authResult.user.isAnonymous
) {
db.collection("users")
.add({
email: authResult.user.email,
expire: new firebase.firestore.Timestamp.now(),
positions: [0, 0, 0],
premium: false
})
.then(() => {
window.location.pathname = "/";
});
}
window.location.pathname = "/";
return false;
}
}
};
ui.start("#firebaseui-auth-container", uiConfig);
I think there are a couple of problems with the flow here, one is general with how async works and the other is specific to FirebaseUI. I'll cover both.
First let's look at the sequence in which your callback code will run:
signInSuccessWithAuthResult: function(authResult) {
// 1. BEGINS RUNNING HERE
let email = authResult.user.isAnonymous
? "guest"
: authResult.user.email;
localStorage.setItem("userEmail", email);
if (
authResult.additionalUserInfo.isNewUser &&
!authResult.user.isAnonymous
) {
// 2. THIS FUNCTION KICKS OFF BUT WILL RETURN IMMEDIATELY
db.collection("users")
.add({
email: authResult.user.email,
expire: new firebase.firestore.Timestamp.now(),
positions: [0, 0, 0],
premium: false
})
.then(() => {
// 4. THIS WOULD RUN LAST, BUT PROBABLY IS ABORTED/SKIPPED DUE TO 3
window.location.pathname = "/";
});
}
// 3. THIS REDIRECT WILL BE TRIGGERED WHILE THE .add() IS EXECUTING async
window.location.pathname = "/";
return false;
}
}
};
So to fix that, you'd need to remove the redirect at 3) and only redirect after the collection has been saved.
BUT! FirebaseUI will automatically redirects to the "success" page when the callback returns. So even if you did the above change, the FirebaseUI redirect would randomly abort the db.collection.add() and reload the page to '/success' the default.
To stop this you have to block the return of the callback, by using async/await, and remove your manual redirect and configure the success url.
const uiConfig = {
signInSuccessUrl: '/success',
callbacks: {
signInSuccessWithAuthResult: async function(authResult) {
// ...
await db.collection("users").add({ ... });
}
}
};
Adding async to the callback allows you to block and await for the db.collection.add to return. Then you shouldn't redirect manually as the signInSuccessUrl does it for you so you'd get a second race-condition.
I've simplified it here, so ensure you don't add any other non-awaited async tasks else they'd race too. (e.g. LocalStorage.setItem() is blocking, but if you used AsyncStorage.setItem() you'd have the same issue and should await that too).

Writing a Testcafe test to assert a loading spinner is visible after making a fetch request

I have the following scenario:
Load page
Expect spinner is hidden
Type username Click search
Expect spinner display
After a few seconds delay, expect spinner to hide
Assert the right user details are displayed
Here is the working demo
I have mocked the network request in my test spec, but I am unable to understand how to assert spinner is visible after I click the search button
Here is my test spec:
import {Selector, RequestMock} from "testcafe";
import mockUser from "../mocks/mockUser.json";
var apiMocks = RequestMock()
.onRequestTo(/\/api\/users/)
.respond(mockUser, 200, {
'access-control-allow-credentials': "*",
'access-control-allow-origin': "*"
})
fixture `When a user is searched`
.page(`http://localhost:3000/`)
.requestHooks(apiMocks);
test("Should fetch user details", async t => {
const spinnerEl = Selector("[data-test-id='spinner']");
await t.expect(spinnerEl.exists).notOk();
await t
.typeText("[data-test-id='txt-search']", "foo")
.click("[data-test-id='btn-search']");
// This line does not work
// await t.expect(spinnerEl.exists).ok();
await t.expect(Selector("[data-test-id='username']").innerText).eql("Foo Bar");
await t.expect(Selector("[data-test-id='userid']").innerText).eql("foo");
})
I am new to TestCafe, could someone help me with this.
Thanks!
It is difficult to check whether the described spinner element is shown due to the following:
It is displayed only during a short period of time. This does not allow TestCafe to check it in time. Using mocks makes the spinner appear only for milliseconds.
TestCafe waits for all requests and does not perform any actions until XHR requests are completed. This means that assertions will not start until your request is finished.
However, it's still possible to work around the issue.
You can use MutationObserver and TestCafe ClientFunctions mechanism.
You can create your element observer using the ClientFunction. The observer will watch for the app element changes. If the spinner element appears the observer will be notified and set the window.spinnerWasShown variable to true.
After the button is clicked, you can check that the windows.spinnerWasShown variable is set to true.
Here is the full example:
import { Selector, RequestMock, ClientFunction } from "testcafe";
import mockUser from "../mocks/mockUser.json";
var apiMocks = RequestMock()
.onRequestTo(/\/api.github.com\/users/)
.respond(mockUser, 200, {
'access-control-allow-credentials': "*",
'access-control-allow-origin': "*"
});
fixture`When a user is searched`
.page(`http://localhost:3000/`)
.requestHooks(apiMocks);
const spinnerWasShown = ClientFunction(() => window.spinnerWasShown);
const observeSpinner = ClientFunction(() => {
var appEl = document.querySelector('.app');
const config = { attributes: true, childList: true };
const callback = function(mutationsList) {
for(let mutation of mutationsList) {
if (mutation.type === 'childList') {
for (var i =0; i < mutation.addedNodes.length; i++ )
window.spinnerWasShown = window.spinnerWasShown || mutation.addedNodes[i].className.indexOf('spinner') > -1;
}
}
};
const observer = new MutationObserver(callback);
observer.observe(appEl, config);
});
test("Should fetch user details", async t => {
const spinnerEl = Selector("[data-test-id='spinner']");
await t.expect(spinnerEl.exists).notOk();
await t.typeText("[data-test-id='txt-search']", "foo");
await observeSpinner();
await t.click("[data-test-id='btn-search']");
await t.expect(spinnerWasShown()).eql(true);
await t.expect(spinnerEl.exists).notOk();
await t.expect(Selector("[data-test-id='username']").innerText).eql("Foo Bar");
await t.expect(Selector("[data-test-id='userid']").innerText).eql("foo");
});

I have created a chat application in which every ten second it takes records from database but i want to show notification at taskbar

I want to show new message notification at taskbar in asp.net MVC or in somewhere to aware user that new message have came.
You can add one Boolean column in you table namely "Seen" with default false value. when user open that message then update that value as true. so you will be easily able get not seen messages for notification. and you can show notification at the top of the page in header section.
We can show desktop notification by javascript function
function createNotification() {
var options = {
body: 'This is the body of the notification',
icon: 'stupidcodes.com.png',
dir: 'ltr'
};
var notification = new Notification("Hi there", options);
notification.onclick = function () {
window.open(document.URL);
};
}
function notifyMe() {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
else if (Notification.permission === "granted") {
createNotification();
}
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
if (!('permission' in Notification)) {
Notification.permission = permission;
}
if (permission === 'granted') {
createNotification();
}
});
}
}
first check throgh ajax function if there is any unread funtion then call this notifyMe() function