I am new to testing using protractor so for testing I have to take screenshots in an angular application for all the different routes in my app. I tried to do it on a small dummy angular app, so I cloned the Tour of heroes repo it has dashboard and Heroes route. I wrote the following code in app.po.ts :
import { browser, element, by } from 'protractor';
export class BlankPage {
navigateTo() {
return browser.get('/heroes');
}
getParagraphText() {
return element(by.tagName('h2')).getText();
}
}
and in app.e2e-spec.ts
import { BlankPage } from './app.po';
import {browser,by,element} from 'protractor';
import { protractor } from 'protractor';
import {createWriteStream} from 'fs' ;
describe('blank App', () => {
let page: BlankPage;
beforeEach(() => {
page = new BlankPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('My Heroes');
browser.takeScreenshot().then((png) =>{
var stream = createWriteStream("heroes.png"); /** change the png file name */
stream.write(new Buffer(png, 'base64'));
stream.end;
});
});
});
The idea was to navigate to heroes route and capture the screenshot. I got the screenshot but
Is there a way I can automate the task of going to all the routes and take screenshots ? In my actual website there are a lot of routes
I think the better solution for you is to add some reporter that will do everything for you, like taking screenshots after each test or after each failed tests and e.t.c.
Take a look at some reporters:
allure-jasmine - Highly recommended.
protractor-jasmine2-screenshot-reporter
protractor-jasmine2-html-reporter
protractor-html-reporter-2
protractor-html-screenshot-reporter
protractor-beautiful-reporter
But If you don't want to add any extra libraries to your project you can just put the browser.takeScreenshot() function to the afterEach function to take a screenshot after each test (it).
For instance:
describe('blank App', () => {
let page: BlankPage;
beforeEach(() => {
page = new BlankPage();
});
afterEach(() =>
browser.takeScreenshot().then((png) =>{
var stream = createWriteStream("heroes.png"); /** change the png file name */
stream.write(new Buffer(png, 'base64'));
stream.end;
});
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('My Heroes');
});
});
I think the best approach for you would be the have a list of all the routes in your application and create a datadriven test to iterate over each one.
You would need a generic navigation function which could get to each page e.g navigateTo(routeName). That code would look something like this.
var routes = [
'homepage',
'myheroes',
'mainpage',
'heroprofile'
]
describe('blank App', () => {
for (let i = 0; i < routes.length; i++) {
it('should display message saying app works', () => {
navigateTo(routes[i]);
browser.takeScreenshot().then((png) => {
var stream = createWriteStream(routes[i] + ".png"); /** change the png file name */
stream.write(new Buffer(png, 'base64'));
stream.end;
});
});
}
});
protractor-image-compare
Really though I would recommend you use the npm package protractor-image-comparison. I've worked with this package and it does make visual validation very straightforward. It allows you to save new baseline images (golden images as you call them) if they are absent and compares them if they are present. The comparison are very sensitive to change but you can set how much of a difference you want to allow.
There would be no database required with this approach.
Note
Be aware also that different browsers take screenshots differently based. Chrome considers the "viewport" to be the visible portion of the browser but I believe in firefox you can screenshot the entire webpage at once.
Related
I have SPA page, all work very good but when user reload page beeing on winners or garage get info :
Cannot GET /Garage. Then have to pick default url. How to set reload function on current page.
https://darogawlik-async-race-api.netlify.app/ (my app)
const navigateTo = url => {
history.pushState(null, null, url)
router()
}
const router = async () => {
const routes = [
{ path: '/Garage', view: garage },
{ path: '/Winners', view: winners },
]
// Test each route for potential match
const potentialMatches = routes.map(route => ({
route,
isMatch: location.pathname === route.path,
}))
let match = potentialMatches.find(potentialMatches => potentialMatches.isMatch)
if (!match) {
match = {
route: routes[0],
isMatch: true,
}
}
const view = new match.route.view(document.querySelector('#main'))
}
window.addEventListener('popstate', router)
document.addEventListener('DOMContentLoaded', () => {
document.body.addEventListener('click', e => {
if (e.target.matches('[data-link]')) {
e.preventDefault()
navigateTo(e.target.href)
}
})
router()
})
window.addEventListener('load', router())
This will be a problem with default document handling in the web host - it is not a page load problem. Eg just click this link to get the problem:
https://darogawlik-async-race-api.netlify.app/Garage
Since you are using path based routing, your web host must serve the default document for all paths, including /Garage and /Winners. As an example, in Node.js Express you write code like this. For other web hosts you either write similar code or there is a configuration option that will do it for you.
// Serve static content for physical files, eg .js and .css files
expressApp.use('/', express.static());
// Serve the index.html for other paths
expressApp.get('*', (request, response) => {
response.sendFile('index.html');
}
According to this post on Netlify, you can add a file something like this. I'm no expert on this platform, but hopefully this gives you the info you need to resolve your issue:
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
I'm looking to simplify my project's testing API where I am aiming for something like this:
testThing((t) => {
t(33);
t(44);
t(42);
})
Now I don't know how to get Jest to show the correct code frames for failed expect's. This is my current stab at an implementation:
const testThing = (callback: any) => {
callback((n: any) => {
test(n.toString(), () => {
expect(n).toBe(42);
});
});
};
Which results in the testThing definition to be shown for every failed test case. Here's a replit if you want to see it in action: https://replit.com/#grgr/jest-frame-issue#thing.test.js
I hope someone can help, I've just converted a Cypress Mocha framework to BDD. Before converting it was running perfectly and the test was running smoothly. Now I've converted it I seem to be getting an error message Cannot read properties of undefined (reading 'mobileHandset'). I never had this issue before so I'm very confused. here is the code and watch this video
Feature:
Feature: End to End Shopping Purchase Validation
Registered user will be able to purchase an item and have it shipped to their country
Scenario: Customer Purchase and delivery
Given I am on the eCommerce page
When I add items to cart
And I confirm shopping cart total
Then I select my delivery country and see a thank for your order notification
Step Definition
import { Given, And, Then, When } from "#badeball/cypress-cucumber-preprocessor";
import Homepage from '../../../support/pageObjects/Homepage'
import orderSummaryPage from '../../../support/pageObjects/orderSummaryPage'
import completeOrderPage from '../../../support/pageObjects/completeOrderPage'
const data = require ('../../../fixtures/example.json');
const homepage = new Homepage()
const StartCheckout = new orderSummaryPage()
const CompleteOrder = new completeOrderPage()
Given(/^I am on the eCommerce page$/, () => {
cy.visit(``+"/angularpractice/")
});
When(/^I add items to cart$/, function() {
homepage.getShopTab().click({force:true})
this.data.mobileHandset.forEach(function(element) {// this custom commad will add items to your cart
cy.AddToCart(element)
});
StartCheckout.getBasketCheckoutButton().click()
});
When(/^I confirm shopping cart total$/, () => {
let sum=0
CompleteOrder.getProductCost().each(($e1, index, $list) =>{
const unitCost=$e1.text()
let res= unitCost.split(" ")
res= res[1].trim()
sum=Number(sum)+Number(res)
}).then(function()
{
cy.log(sum)
})
});
Then(/^I select my delivery country and see a thank for your order notification$/, () => {
StartCheckout.getStartCheckoutButton().click()
CompleteOrder.getShippingCountry().type('United Kingdom')
CompleteOrder.getShippingCountryConfirm().click()
CompleteOrder.getTermsConditionsCheckbox().click({force: true})
CompleteOrder.getPurchaseButton().click()
CompleteOrder.getPurchaseAlert().then(function(element){
const actualText= element.text()
expect(actualText.includes('Success')).to.be.true
})
});
Here is the data
{
"name": "MY_NAME",
"gender": "Female",
"mobileHandset": ["Blackberry", "Nokia Edge"]
}
BeforeEach
beforeEach(function()
{
cy.fixture('example').then(function(data){
this.data=data
})
})
After discussion I moved the BeforeEach file to Support. Still getting the original error
You don't need to import the data fixture if you already have it in the cypress/fixtures folder.
You can load the fixture in the Before hook before your tests.
import {
Given,
And,
Then,
When,
Before
} from "#badeball/cypress-cucumber-preprocessor";
//...
Before(function() {
cy.fixture('example').then((data) => {
this.data = data;
});
});
//...
Your beforeEach() should be working, but it's not necessary you can just refer to data instead of this.data.
const data = require ('../../../fixtures/example.json'); // data available anywhere in this step
...
When(/^I add items to cart$/, () => {
...
data.mobileHandset.forEach(element => {
cy.AddToCart(element)
})
...
})
The convention is to use cy.fixture()
When(/^I add items to cart$/, () => {
...
cy.fixture('example.json').then(data => { // no ../.. needed
data.mobileHandset.forEach(element => {
cy.AddToCart(element)
})
})
...
});
I'm trying to make a web worker to prevent stalling the React main thread. The worker is supposed to read an image and do various things.
The app was created using create-react-app.
Currently I have
WebWorker.js
export default class WebWorker {
constructor(worker) {
const code = worker.toString();
const blob = new Blob(['('+code+')()'], {type: "text/javascript"});
return new Worker(URL.createObjectURL(blob), {type: 'module'});
}
}
readimage.worker.js
import Jimp from "jimp";
export default () => {
self.addEventListener('message', e => { // eslint-disable-line no-restricted-globals
if (!e) return;
console.log('Worker reading pixels for url', e.data);
let data = {};
Jimp.read(e.data).then(image => {
// jimp does stuff
console.log('Worker Finished processing image');
})
postMessage(data);
})
};
And then in my React component AppContent.js I have
import WebWorker from "./workers/WebWorker";
import readImageWorker from './workers/readimage.worker.js';
export default function AppContent() {
const readWorker = new ReadImageWorker(readImageWorker);
readWorker.addEventListener('message', event => {
console.log('returned data', event.data);
setState(data);
});
// callback that is executed onClick from a button component
const readImageContents = (url) => {
readWorker.postMessage(url);
console.log('finished reading pixels');
};
}
But when I run it, I get the error
Uncaught ReferenceError: jimp__WEBPACK_IMPORTED_MODULE_0___default is not defined
How can I properly import a module into a web worker?
EDIT:
As per suggestions from Kaiido, I have tried installing worker-loader, and edited my webpack.config.js to the following:
module.exports = {
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: 'worker-loader' }
}
]
}
};
But when I run it, I still get the error
Uncaught ReferenceError: jimp__WEBPACK_IMPORTED_MODULE_0__ is not defined
I'm not too much into React, so I can't tell if the module-Worker is the best way to go (maybe worker-loader would be a better solution), but regarding the last error you got, it's because you didn't set the type of your Blob when you built it.
In this case, it does matter, because it will determine the Content-Type the browser sets when serving it to the APIs that fetch it.
Here Firefox is a bit more lenient and somehow allows it, but Chrome is picky and requires you set this type option to one of the many javascript MIME-types.
const script_content = `postMessage('running');`;
// this one will fail in Chrome
const blob1 = new Blob([script_content]); // no type option
const worker1 = new Worker(URL.createObjectURL(blob1), { type: 'module'});
worker1.onerror = (evt) => console.log( 'worker-1 failed' );
worker1.onmessage = (evt) => console.log( 'worker-1', evt.data );
// this one works in Chrome
const blob2 = new Blob([script_content], { type: "text/javascript" });
const worker2 = new Worker(URL.createObjectURL(blob2), { type: 'module'});
worker2.onerror = (evt) => console.log( 'worker-2 failed' );
worker2.onmessage = (evt) => console.log( 'worker-2', evt.data );
But now that this error is fixed, you'll face an other error, because the format import lib from "libraryname" is still not supported in browsers, so you'd have to change "libraryname" to the path to your actual script file, keeping in mind that it will be relative to your Worker's base URI, i.e probably your main-page's origin.
I experienced the same problem. Firefox could not show me where exactly the error was (in fact it was plain misleading...) but Chrome did.
I fixed my problem by not relying on an import statement (importing one of my other files) which would only have worked within a React context. When you load a Worker script (via the blob()
/ URL() hack), it has no React context (as it is loaded at runtime and not at transpile time). So all the React paraphernalia __WEBPACK__blah_blah is not going to exist / be visible.
So... within react... import statements in worker files will not work.
I haven't thought of a workaround yet.
Sentry by defaults has integration for console.log to make it part of breadcrumbs:
Link: Import name: Sentry.Integrations.Console
How can we make it to work for bunyan logger as well, like:
const koa = require('koa');
const app = new koa();
const bunyan = require('bunyan');
const log = bunyan.createLogger({
name: 'app',
..... other settings go here ....
});
const Sentry = require('#sentry/node');
Sentry.init({
dsn: MY_DSN_HERE,
integrations: integrations => {
// should anything be handled here & how?
return [...integrations];
},
release: 'xxxx-xx-xx'
});
app.on('error', (err) => {
Sentry.captureException(err);
});
// I am trying all to be part of sentry breadcrumbs
// but only console.log('foo'); is working
console.log('foo');
log.info('bar');
log.warn('baz');
log.debug('any');
log.error('many');
throw new Error('help!');
P.S. I have already tried bunyan-sentry-stream but no success with #sentry/node, it just pushes entries instead of treating them as breadcrumbs.
Bunyan supports custom streams, and those streams are just function calls. See https://github.com/trentm/node-bunyan#streams
Below is an example custom stream that simply writes to the console. It would be straight forward to use this example to instead write to the Sentry module, likely calling Sentry.addBreadcrumb({}) or similar function.
Please note though that the variable record in my example below is a JSON string, so you would likely want to parse it to get the log level, message, and other data out of it for submission to Sentry.
{
level: 'debug',
stream:
(function () {
return {
write: function(record) {
console.log('Hello: ' + record);
}
}
})()
}