Gerkin and Cucumber in Angular 5: Undefined - protractor

When I try to create a test using Cucumber and Gherkin I get a strange error. I show you the error first, then the files login.step.ts and login.po.ts:
// Error:
Undefined. Implement with the following snippet:
When('Enter the card number in the box', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
// login.step.ts
import { expect } from 'chai';
const { Given, When, Then, Before } = require('cucumber');
import { browser, by, element } from 'protractor';
import { LoginPage } from './login.po';
let login: LoginPage;
Before(() => {
login = new LoginPage();
});
Given(/^Entering in Login$/, { timeout: 10 * 5000 }, async () => {
await browser.get('http://localhost:49152/login');
});
When(/^Enter the card number in the box$/, () => {
// login.setCardNumber('1234').then((txt) => {
// return 'ready!?';
// })
login.setCardNumber('1234');
});
// login.po.ts
import { browser, by, element, until } from 'protractor';
export class LoginPage {
navigateTo() {
return browser.get('/login');
}
setCardNumber(cardNumber) {
const input = element(by.css('#box'));
return input.sendKeys(cardNumber);
}
}
The first test passes successfully, but in the second test, the process ends in error.
[EDIT]
Adding the protractor.conf.js file:
exports.config = {
allScriptsTimeout: 11000,
specs: [
// './e2e/**/*.e2e-spec.ts',
'./e2e/features/*.feature'
],
capabilities: {
'browserName': 'chrome',
chromeOptions: {
args: ['disable-infobars']
},
metadata: {
browser: {
name: 'chrome',
version: '58'
},
device: 'Xubuntu Linux',
platform: {
name: 'Linux',
version: '16.04'
}
}
},
directConnect: true,
frameworkPath: require.resolve('protractor-cucumber-framework'),
plugins: [{
package: 'protractor-multiple-cucumber-html-reporter-plugin',
options: {
automaticallyGenerateReport: true,
removeExistingJsonReportFile: true
}
}],
cucumberOpts: {
require: ['./e2e/steps/**/*.ts', './e2e/support/*.ts'],
tags: [],
dryRun: false,
compiler: [],
format: 'json:reports/results.json',
strict: true
},
baseUrl: 'http://localhost:4200/',
SELENIUM_PROMISE_MANAGER: false,
framework: 'custom',
onPrepare() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
}
};

remove the double quote " behind box in /^Enter the card number in the box"$/

I found the answer to my problem. I only had to include the following configuration line to my Before() step in my test:
browser.ignoreSynchronization = true;
According to what I read in different places, it seems that Chrome is looking to perform some task with sockets, and with this line we are disabling this task.

Related

How to tree-shake Lodash and Mui imports in Storybook 5

I'm using Mui and Lodash in my CRA project with Storybook 5.
I successfully tree-shake both Mui and Lodash imports using babel-plugin-import in CRA, using the following .bablerc.js
module.exports = {
presets: ["react-app", "#babel/preset-typescript"],
plugins: [
[
"babel-plugin-import",
{
libraryName: "#material-ui/core",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"core",
],
[
"babel-plugin-import",
{
libraryName: "#material-ui/icons",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"icons",
],
["lodash"],
],
};
However I am unable to do the same in Storybook 5. When I try using the same config in Storybook (copying over to .storybook/.babelrc.js), the babel config gets loaded, but results in no improvement in Storybook load times (Mui icons still seem to be loading for about a minute). Removing the presets
from babel config doesn't help either.
Storybook is hosted in the same root directory as my CRA, sharing node_modules.
How can I get the import tree-shaking to work in Storybook 5?
Here are my configs:
// .storybook/presets.js
module.exports = ['#storybook/preset-create-react-app'];
// .storybook/webpack.config.js
module.exports = function({ config }) {
// https://github.com/storybookjs/storybook/issues/6974#issuecomment-499903328
config.module.rules.unshift({
test: /\.stories.js$|\.stories.jsx$|\.stories.tsx$|\.stories.ts$/,
loaders: [require.resolve('#storybook/source-loader')],
enforce: 'pre',
});
return config;
};
// .storybook/.babelrc.js
module.exports = {
presets: ["react-app", "#babel/preset-typescript"],
plugins: [
[
"babel-plugin-import",
{
libraryName: "#material-ui/core",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"core",
],
[
"babel-plugin-import",
{
libraryName: "#material-ui/icons",
libraryDirectory: "esm",
camel2DashComponentName: false,
},
"icons",
],
["lodash"],
],
};
// .storybook/config.js
iimport { addDecorator, addParameters, configure } from "#storybook/react";
import { withKnobs } from "#storybook/addon-knobs";
import { withConsole } from "#storybook/addon-console";
import { INITIAL_VIEWPORTS } from "#storybook/addon-viewport";
import "../src/config";
import withIntl from "./decorators/intl";
import withReduxStoreAndConnectedRouter from "./decorators/reduxStoreWithDependentProviders";
import stylesProvider from "./decorators/stylesProvider";
import setup from "./decorators/setup";
const req = require.context("../src", true, /stories.tsx$|stories.ts$/);
const loadStories = () => req.keys().forEach((filename) => req(filename));
addDecorator(setup);
addDecorator(stylesProvider);
addDecorator(withKnobs);
addDecorator(withIntl);
addDecorator(withReduxStoreAndConnectedRouter);
addDecorator((storyFn, context) =>
withConsole(consoleConfig)(storyFn)(context)
);
addParameters({
viewport: {
viewports: INITIAL_VIEWPORTS,
},
});
addParameters({
backgrounds: [
{ name: "darkGray", value: "#34373c" },
{ name: "gray", value: "#A0A0A0" },
{ name: "lightGray", value: "#F0F0F0" },
],
});
configure(loadStories, module);

TypeError: protractorImageComparison is not a constructor

I try to run comparison tests and get Error: TypeError: protractorImageComparison is not a constructor. please advice
The same code worked in the full angular project but i needed to sperated the testing from the code.
i added my conf.file and the spec file
//protractor.conf.js:
const { SpecReporter } = require('jasmine-spec-reporter').SpecReporter;
exports.config = {
allScriptsTimeout: 15000,
specs: [
'src/tests/*.e2e-spec.js'
],
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['no-sandbox']
}
},
directConnect: true,
baseUrl: 'https://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare: function() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
const protractorImageComparison =require('protractor-image-comparison');
browser.driver.manage().window().setSize(1366, 768);
browser.protractorImageComparison = new protractorImageComparison({
baselineFolder: '.\\e2e\\src\\screenshots\\baseline',
screenshotPath: '.\\e2e\\src\\screenshots\\actual_screenshots',
autoSaveBaseline: true
});
},
};
//test
import {browser } from 'protractor';
import {LoginPage} from '../pages/login.po';
describe('login page', function() {
beforeEach(function()
{
LoginPage.navigateTo();
});
it('login page should match the design', () => {
expect(browser.protractorImageComparison.checkScreen('login_Page')).toEqual(0);
});
});
If you are using the latest protractor-image-comparison, it appears that it says you should use it as a plugin. The constructor itself has been moved to https://github.com/wswebcreation/protractor-image-comparison/blob/master/lib/index.ts#L9 and is not exported.
The plugin should be added in your Protractor config per the readme file:
plugins: [
{
// The module name
package: 'protractor-image-comparison',
// Some options, see the docs for more
options: {
baselineFolder: join(process.cwd(), './baseline/'),
formatImageName: `{tag}-{logName}-{width}x{height}`,
screenshotPath: join(process.cwd(), '.tmp/'),
savePerInstance: true,
// ... more options
},
},
],

WebDriverError: Could not start Browser / Emulator error

Oflate , I have been observing below error when ran my protractor tests on browserstack.
"UnhandledPromiseRejectionWarning: WebDriverError: Could not start Browser / Emulator"
Here is my protractor config file.
let browserstack = _.defaults({
user: process.env.BROWSERSTACK_USERNAME,
key: process.env.BROWSERSTACK_ACCESS_KEY
}, {
user: '**',
key: '**'
});
let timeoutMultiplier = 2;
exports.makeDefaultCapabilities = function(that) {
return {
browserName: 'chrome',
chromeOptions: {
prefs: {
credentials_enable_service: false,
},
loggingPrefs: {
driver: 'WARNING',
server: 'WARNING',
browser: 'INFO'
},
'browserstack.user': browserstack.user,
'browserstack.key': browserstack.key,
'browserstack.debug': true,
build: that.params.BUILD_NUMBER || '(unknown)',
maxInstances: 2,
name: that.baseUrl,
}
};
exports.config = {
suites: {
e2e: [
'*/*.spec.js'
]
},
SELENIUM_PROMISE_MANAGER: false,
baseUrl: undefined,
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 60 * 1000 * timeoutMultiplier,
realtimeFailure: true
},
maxSessions: 1,
params: {
BUILD_NUMBER: undefined,
CI: undefined,
TIMEOUT_MULTIPLIER: timeoutMultiplier
},
seleniumAddress: 'https://hub-cloud.browserstack.com/wd/hub',
useAllAngular2AppRoots: true,
getMultiCapabilities: function() {
return new Promise(function(resolve) {
let capabilities = [];
capabilities.push({
os: 'OS X',
os_version: 'High Sierra'
});
resolve(capabilities);
});
},
onPrepare: function() {
browser.manage().window().maximize();
jasmine.getEnv().addReporter(failFast.init());
let reporter = new SpecReporter();
jasmine.getEnv().addReporter(reporter);
}
};
Test that is failing :
calling function :
async clickButton() {
await browser.waitForAngularEnabled(false);
await waitForEl(this.Button);
await browser.sleep(10000);
await this.Button.click();
await browser.sleep(10000);
await this.stopButton.click();
await waitForElAbsence(this.Bar);
await browser.waitForAngularEnabled(true);
}
used above calling function in below spec:
it('should check if button is clicable', async function() {
let po = new check({
url
});
await po.go();
await po.clickButton();
});
Has any one experienced it before ? Also the error is seen only browserstack and not on my local computer. Also the test i pasted is not the only one failing . Tests are failing randomly with this error.
I have protractor v5.3.2

Getting error in setting up log4js-protractor-appender in protractor

My Conf.js looks like below:
// An example configuration file.
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directory when
// protractor is called.
specs: ['test_spec1.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
},
var log4js = require('log4js');
beforeLaunch:function(){
if (fs.existsSync('./logs/ExecutionLog.log')) {
fs.unlink('./logs/ExecutionLog.log')
}
log4js.configure({
appenders: [
{ type: 'log4js-protractor-appender', category: 'protractorLog4js' },
{
type: "file",
filename: './logs/ExecutionLog.log',
category: 'protractorLog4js'
}
]
});
},
onPrepare: function() {
browser.logger = log4js.getLogger('protractorLog4js');
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmineReporters.JUnitXmlReporter('./Reports', true, true));
}
};
I get following error on running command "protractor conf.js"
You need to move the var log4js = require('log4js'); line to the top of the conf file, above the exports.config ={ .. } block. Also use const instead of var

Karma debugging in Chrome no longer working

We are working on an Angular project where we are using Karma/Jasmine for our testing environment. We've been using the karma-chrome-launcher for debugging the tests and it was working great. For some reason, it has stopped working lately. I can't figure out why though, as we haven't changed anything regarding that pipeline. We tried updating to latest Karma (1.4.1), but that didn't help. Has anyone else seen this issue and been able to fix it? Help is appreciated. I've attached two images of what the Chrome inspector looks like when you first open the debugger and then after setting a breakpoint and hitting Refresh (it should look the same as the 1st image, but doesn't) edit: karma.config at bottom as well
'use strict';
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
var patterns = wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js')
])
.concat(pathSrcHtml)
.concat('karmaMobileFramework/*.js');
var files = patterns.map(function(pattern) {
return {
pattern: pattern
};
});
files.push({
pattern: path.join(conf.paths.src, '/assets/**/*'),
included: false,
served: true,
watched: false
});
return files;
}
module.exports = function(config) {
var configuration = {
files: listFiles(),
singleRun: false,
autoWatch: true,
preprocessors : {
'/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src + '/',
moduleName: 'directive-templates'
},
logLevel: 'WARN',
frameworks: ['jasmine', 'jasmine-matchers', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-angular-filesort',
'karma-coverage',
'karma-jasmine',
'karma-jasmine-matchers',
'karma-ng-html2js-preprocessor',
'karma-htmlfile-reporter',
'karma-junit-reporter'
],
coverageReporter: {
type : 'html',
dir : 'reports/coverage/',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'cobertura', subdir: 'report-jenkins' }
]
},
reporters: ['progress', 'html', 'junit'],
junitReporter: {
outputDir: 'reports/tests/',
outputFile: 'test-results.xml',
useBrowserName: false
},
htmlReporter: {
outputFile: 'reports/tests/results.html',
pageTitle: 'BOLT Unit Tests'
},
proxies: {
'/assets/': path.join('/base/', conf.paths.src, '/assets/')
}
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor is added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
config.set(configuration);
};