I have written webui automated testing cases of a webUI using Casperjs.
it includes:
home.js (checks home page in log-in state)
premium.js (checks premium user in log-in state)
catagories.js (checks categories page in log-in state)
Favorite.js (checks favorite page in log-in state)
I can run these tests successfully.
Is there a way to run them all at once? So that I can test all the pages at once when I want?
I think you can do it by creating a single script and create different functions to test each of the functionalities. The following code may give some idea
casper.start();
var running = 1;
var home_js = function(){
//your casper steps in home.js
};
var premium_js = function(){
// your steps in premium.js
// at end set running = 0 to stop the execution
};
var controller = function(){
if(running==1){
home_js.call(this);
premium_js.call(this);
casper.run(controller);
}else{
this.exit();
}
}
casper.run(controller);
Related
I implemented Application Insigths in the frontend applciation and I want to disable/enable it based on a variable that can change over the lifetime of the applications. (e.g. user declined Application Insights consent => Disable Telemetry)
What I tried is:
appInsights.appInsights.config.disableTelemetry = true
however if I try to enable it back setting disableTelemetry =false this is not working anymore.
Is anything else that I need to make to persist this change or is there another way of doing this?
You could use a telemetry filter for that:
var filteringFunction = (envelope) => {
if (condition) {
return false; // Do not send telemetry
}
return true; // Do send the telemetry
};
Register the filter like this:
appInsights.addTelemetryInitializer(filteringFunction);
While Peter's answer is correct, I have different approach where instead of using telemetry filters we can stop the application insights object itself from starting to log to app insights.
Here in the following code based on the value of the variable a it will start the app insight service.
So, we will run appInsights.start(); only for a particular for value of variable a.
import { createRequire } from "module";
const require = createRequire(import.meta.url);
let appInsights = require('applicationinsights');
appInsights.setup("<Your connection String>")
.setAutoCollectConsole(true, true);
var a = 10 ;
if(a==10)
{appInsights.start();}
console.log("Hello World ");
Here I am running the code twice but with different value of variable a.
Here in application insights one log appear.
Personally I see playwright as a tool that goes into the direction of system/end-to-end tests. So I used playwright + jest to build-up user journeys and integrated them in a CI/CD process.
Since playwright created it's own test runner with useful features like taking videos and trace on failures, it would make sense to switch from jest to #playwright/test. On their home page playwright recommends to use test fixtures so I definitly want to include them in the switch.
In the following I will take amazon as an example.
With playwright + jest the first thing that I did was to create a function for generic setup of the environment:
function setupSuite({ browserOptions, userConfig }){
// create playwright browser and use browserOptions as overrides
// create page from browser
// register self-implemented trace and screenshot reporters to page
// go to baseUrl of current environment (e.g. local, branch etc..)
// click on cookie banner, since it's blocking the UI
// create a user based on userConfig (e.g. user has amazon prime user? payment options? etc.)
// return { browser, page, user, ... }
}
And of course a function to clean up everything again:
function teardownSuite(suite){
// close browser
// delete user
// etc..
}
Then I would use a file for each user journey. In case of amazon a user journey could be the successful processing of an order:
describe("Successful Order", () => {
let suite
beforeAll(async () => {
const userConfig = { isPrime: false, paymentOptions: [ "paypal", "visa" ] }
suite = await setupBrowser({ userConfig })
// I actually extracted that logic in a function to be able to use it in other tests too,
// but just want to make clear whats happening here
const { page, user } = suite
await page.fill(".login-username-input", user.username)
await page.fill(".login-password-input", user.password)
await page.click(".login-submit-button")
})
afterAll(() => teardownSuite(suite))
test("search for toothbrush with suggestions", async () => {
const { page } = suite
await page.fill(".search-input", "tooth")
await page.click("text='toothbrush")
// hit enter
// do some assertions to check if the search was really successful
})
test("click on first item and add to chart", async () => {
// page actions and assertions
})
test("go back, click on second item and add to chart", async () => {
// page actions and assertions
})
test("go to chart and pay", async () => {
// page actions and assertions
})
test("check order confirmation mail", async () => {
// page actions and assertions
})
})
As you can see I split up my test in logical parts to make it more readable and also to see at which step (test block) it failed.
What would be the best way to migrate this to #playwright/test + fixtures?
How would you migrate setupSuite / teardownSuite ? Yes you could use a fixture, but setupSuite expects arguments like the userConfig . Is it possible to have parameterized fixtures?
How would you structure tests with fixtures? If you want to simulate complete user journey the tests are getting bigger than just testing a login for example. A test block would then have a lot of lines without the possibility to structure them.
Is it possible to setup a page so it's shared accross all tests? The beforeAll hook doesn't receive any page and the each test block always receives its own page. This means that there is no connection between test blocks. If you create a page manually in beforeAll and use the same page instance in every test it would probably be a bad practice and video and tracing would probably not work.. so what can be done here?
Are user journey like tests actually bad? I feel like they can't be combined well with the fixture approach of playwright as mentioned in the docs. Fixtures in playwright feel like very data-driven which doesn't really fit to end-to-end testing IMO.
I am trying to test an angular app in protrator and I do not understand something.
I put this line there
beforeEach(function() {
browser.get('http://juliemr.github.io/protractor-demo/');
});
And I want to refenrence the elements of an HTML form using this line:
fdescribe('Protractor Demo App', function() {
var goButton = element(by.id('gobutton'));
...and test its result
In protractor we do not put the test files corresponding to a specific .ts file in its folder, so this test searches in the whole project for an id gobutton or it searches for an id gobutton that belongs specifically to the link that I have put on browser.get()??
And my next question is if the page I wanna test requires a login, can I just use browser.get url of this page and test the elements or I should do the part of logging during my test?
And is it normal if my browser closes itself afterexecuting one test, or it should stay opened?
This is a lot of questions ;)
Protractor will search the whole DOM for the element's id. Even if you work with the mentioned *.po.ts files in the component folders, they'll eventually only deliver the elements id represented by a string you then search via element(by.id()).
If a login is required, you'll have to consider it during your test. I doubt that you can bypass the login mechanism, except the login can be switched off on the testing stage and switched on on the production stage.
Yes, it is the standard behavior of Protractor to close the browser after having finished the test. This is because you have your protocol file afterwards.
This is how my protractor.conf.js looks like. The given path target is located on the level of /src.
let HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
// always create test-report.html, screen shots only in case of failures
let reporter = new HtmlScreenshotReporter({
dest: 'target/test-screenshots',
filename: 'test-report.html',
reportOnlyFailedSpecs: false,
captureOnlyFailedSpecs: true,
pathBuilder: function (currentSpec, suites, browserCapabilities) {
// will return chrome/your-spec-name.png
return browserCapabilities.get('browserName') + '/' + currentSpec.fullName;
}
});
exports.config = {
...
beforeLaunch: function () {
return new Promise(function (resolve) {
reporter.beforeLaunch(resolve);
});
}
I have an Angular app used to track hours worked by the user. When the user adds a new job, they are taken through a wizard, with each page/controller adding a new property to the job object. Once the wizard is complete, the user can start tracking by navigating to the jobs home page from the app main page.
It is, however, possible to exit the wizard before it is completed (via the back button) and then navigate to the home page of the job. What I need is for the controller for that home page to redirect to the appropriate wizard page for whichever job property is missing.
The job variable is retrieved from local storage at the start of the controller code.
var job = DatastoreService.objectJob();
job.initFromHash($routeParams.jobHash);
function checkJobProps(prop, route){
if(!job.data.hasOwnProperty(prop))
$location.path('/wizard/add-position/' + $routeParams.jobHash + '/' + route);
}
checkJobProps('taxSettings', 'tax');
checkJobProps('payrollSettings','payroll-opt');
checkJobProps('breaks', 'breaks');
checkJobProps('allowances', 'allowances');
checkJobProps('deductions', 'deductions');
checkJobProps('generalSettings', 'general-settings');
There is code below this on the controller that breaks if certain properties are not available. None of these function calls execute fast enough to prevent errors. They will redirect, but not elegantly and it will also always be the last one in the list that takes effect.
Do I do this with a promise? The navigation that is used from the home page of the app to the home page of each job is a directive so, I guess it may be possible to init the job from the $routeParams.jobhash and check these properties within the directive, but I would have to learn more about directives first.
Any help would be much appreciated.
$location.path() is asynchronous and will not prevent the code that follows it from executing. You will have to manually stop the execution with a return statement.
Note that the return statement must belong to the controller function block. You cannot put it inside another function since that will only stop the execution of that specific function.
Something along these lines should work:
var job = DatastoreService.objectJob();
job.initFromHash($routeParams.jobHash);
var redirectPath;
function checkJobProps(prop, route) {
if (redirectPath || job.data.hasOwnProperty(prop)) return;
redirectPath = '/wizard/add-position/' + $routeParams.jobHash + '/' + route;
}
checkJobProps('taxSettings', 'tax');
checkJobProps('payrollSettings', 'payroll-opt');
checkJobProps('breaks', 'breaks');
checkJobProps('allowances', 'allowances');
checkJobProps('deductions', 'deductions');
checkJobProps('generalSettings', 'general-settings');
if (redirectPath) return $location.path(redirectPath);
... rest of the code ...
I'm started using a combination of KnockoutJS (2.2.1), SammyJS (0.7.4) and PagerJS (latest from github with jquery hashchange) to create a single page app and I've run into a problem with the routes as they do not work in Chrome Version 24.0.1312.57 m or Firefox 16.0 (for some reason it actually works in IE7).
Using sammyjs I've specified the routes that the app should react on and their corresponding actions, for example loading user data. The same routes are used in pagerjs to specify which page to display. For some reason the sammyjs code is executed but not the pagerjs code.
When updating the route, for example going from #!/ to #!/user, pagerjs doesn't switch to the new page, but data is updated as expected when switching between #!/user?uid=123 and #!/user?uid=321 . However, when removing the sammyjs code it works - the switch between pages works but data will of course not update properly.
It seems like SammyJS terminates further execution by pagerjs, but as I'm quite new to these libraries it might very well be my code misbehaving. Greatful for any insights.
The javascript code looks something like this:
var UserModel = function () {
var self = this;
self.userId = null;
self.user = ko.observable();
self.userid = ko.observable();
// Load
self.load = function(userId) {
self.loadUser(userId);
};
// Load user data
self.loadUser = function(userId) {
console.log('Loading user data');
};
// Client-side routes
Sammy(function () {
// Overview - datatables in tabs
this.get('#!/', function () {
console.log('Start page');
});
// User - details
this.get('#!/user', function () {
console.log('user page');
self.userId = this.params.uid;
self.load(self.userId);
});
}).run();
}
// Renders user info
$(document).ready(function () {
if ($('#user-info').length) {
var userModel = new UserModel();
pager.extendWithPage(userModel);
ko.applyBindings(userModel);
// Load initial data via ajax
userModel.load();
pager.Href.hash = '#!/';
pager.startHashChange();
}
$('.dropdown-toggle').dropdown();
});
And here goes the HTML with the pagerjs data-bindings:
<div class="container">
<div data-bind="page: {id: 'start'}">
Startpage
</div>
<div data-bind="page: {id: 'user', params: ['uid']}">
User page
</div>
</div>
I think I got it.
You need to add
this.get(/.*/, function() {
console.log("this is a catch-all");
});
after your last this.get. Then Sammy doesn't stop the event.
I've got it working by changing PagerJS to use the naïve history manager instead of jQuery hashchange. In other words this line:
pager.startHashChange();
was changed to:
pager.start();
As of magic it also works in IE7 even if the docs at http://pagerjs.com states it doesn't. Well, for me it does work
// 1. iff using naïve hashchange - wont work with IE7
pager.start();
As long as you include the hashchange plugin pager.start() will use it.
Is the same as the naïve, but you need to include the jQuery hashchange plugin first.
http://pagerjs.com/demo/#!/navigation/setup