I'm trying to run a very simple set of protractor tests, however, when i run the "yarn e2e" command, i got the following error:
import { browser } from "protractor";
^
SyntaxError: Unexpected token {
The code in protractor-config.ts where the error occurs is:
import { browser } from "protractor";
exports.config = {
allScriptsTimeout: 20000,
specs: ['./spec/spec.ts'],
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 720000
},
capabilities: {
'browserName': 'chrome',
},
directConnect: true,
framework: 'jasmine',
SELENIUM_PROMISE_MANAGER: false,
onPrepare: function () {
browser.driver.manage().window().setSize(1280, 1024);
}
}
What i've tried:
Changing
import { browser } from "protractor";
to
const browser = require('protractor');
Changing "target": "es5" to es6 in my tsconfig.json
But non of this options made any difference!
Anyone has any idea on what can this be? Thanks a lot in advance.
Your protractor.config.js should contain :
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json' // if you have one
});
This part is the one telling protractor how to handle typescript. This part of code is from angular-cli, so I suggest you to create a new angular app from scratch with ng new myapp and compare the config (protractor is working by default)
Related
I have a node application that compiles typescript files to a dist folder and then serves these files as lambda resolvers via aws cdk. Here is an example of my setup:
The code
register.ts
import ValidateUserFields from '../utils/forms';
exports.main = async function (event: any, context: any) {
return {
statusCode: 200,
};
}
register-lambda-config.ts
import { Construct } from 'constructs';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
export class FrontendService extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
const api = new apigateway.RestApi(this, 'frontend-api', {
restApiName: 'Frontend Service',
description: 'This service serves the frontend.',
});
const functionName = 'register';
const handler = new lambda.Function(this, functionName, {
functionName,
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromAsset('dist/src/lambda'),
handler: 'register.main',
});
const registerIntegration = new apigateway.LambdaIntegration(handler, {
requestTemplates: { 'application/json': '{ "statusCode": "200" }' },
});
const registerResource = api.root.addResource('register');
registerResource.addMethod('POST', registerIntegration);
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2018",
"module": "commonjs",
"moduleResolution": "node",
"lib": ["es2018"],
"declaration": true,
"strict": true,
"noImplicitAny": false,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"esModuleInterop": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": false,
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"outDir": "dist",
"typeRoots": ["./node_modules/#types"]
},
"exclude": ["node_modules", "cdk.out", "./dist/**/*"]
}
And finally here is the script part of my package.json file:
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"cdk": "cdk",
"bootstrap": "cdk bootstrap",
"deploy": "cdk deploy && rimraf cdk.out",
"destroy": "cdk destroy",
"run-same-local-fe-api": "sam local start-api -p 4000 -t ./template.yaml",
"dev": "npm run build && npm run synth && concurrently --kill-others \"npm run watch\" \"npm run run-same-local-fe-api\"",
"synth": "cdk synth --no-staging > template.yaml"
},
The problem
When I run npm run dev it compiles my typescript files to the dist folder in the same structure as what I have in my src folder (where all my typescript files live). I however run into the following error if I have any imports in my register.ts file:
{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot
find module '../utils/forms'\nRequire stack:\n-
/var/task/register.js\n- /var/runtime/UserFunction.js\n-
/var/runtime/index.js","stack":["Runtime.ImportModuleError: Error:
Cannot find module '../utils/forms'","Require stack:","-
/var/task/register.js","- /var/runtime/UserFunction.js","-
/var/runtime/index.js"," at _loadUserApp
(/var/runtime/UserFunction.js:202:13)"," at
Object.module.exports.load (/var/runtime/UserFunction.js:242:17)","
at Object. (/var/runtime/index.js:43:30)"," at
Module._compile (internal/modules/cjs/loader.js:1085:14)"," at
Object.Module._extensions..js
(internal/modules/cjs/loader.js:1114:10)"," at Module.load
(internal/modules/cjs/loader.js:950:32)"," at Function.Module._load
(internal/modules/cjs/loader.js:790:12)"," at
Function.executeUserEntryPoint [as runMain]
(internal/modules/run_main.js:75:12)"," at
internal/main/run_main_module.js:17:47"]}
This happens for imports from relative local files (like '../utils/forms' as shown in the code above) but also for imports from node_modules. When I look into the compiled register.js file in the dist folder I see that it has made an attempt to parse the import:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const forms_1 = __importDefault(require("../utils/forms"));
const bucketName = process.env.BUCKET;
exports.main = async function (event, context) { ...
however it shows the error message above. I have tried using require instead of import but it was the same result...
Any help would be greatly appreciate! Thanks
Stated that this is really hard to answer without a minimal reproducible example; I would at least suggest to avoid any require and exports, and to use only import / export statements and following in tsconfig.json.
{
"compilerOptions": {
"module": "esnext"
}
}
Well.. I do understand that you want your main function to look something like this:
// final result written in javascript
exports.main = async function (event, context) {
return {
statusCode: 200,
};
}
But... using module.exports in Typescript is not the way to achieve that. Instead, Typescript using export directive (no s at the end of it) to define which parts of your code should be export. It's then up to your tsconfig.json file to determine which syntax will be used in order to represent this export (this is actually a part of Typescript engine)
So... a script written like this in Typescript
export async function main(event: any, context: any) {
return {
statusCode: 200,
};
}
Will be parse in Typescript as follow (I've used module: commonjs to achieve below result)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = void 0;
async function main(event, context) {
return {
statusCode: 200,
};
}
exports.main = main;
//# sourceMappingURL=test.js.map
Please note how the resulted js file correctly use modile.exports and main as you intended
In short: when using Typescript, please use the language directives and let the engine to do the rest for you. This way - a single source of code can be deployed for different environment without requireing changing your app logic. Neat!
What needs to be changed in below karma.config in order to resolve below error
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
// 'node_modules/#zxing/library/*.js'
// 'assets/#zxing/library/esm/browser/BrowserMultiFormatReader.js'
'assets/#zxing/library/*.js',
],
exclude: [
"assets/other.min.js"
],
preprocessors: {
'app/**/*.html': "ng-html2js",
'app/views/**/!(*spec).js': ['coverage']
},
reporters: ['progress', 'html', 'coverage'],
port: 3000,
colors: true,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true,
concurrency: Infinity,
coverageReporter : {
type : 'html',
dir : 'coverage/',
subdir: '.',
check: {
global: {
....,
.....
},
each: {
....,
....
}
}
},
htmlReporter: {
outputDir: 'karma_html',
namedFiles: true,
reportName: 'sample_spec_report'
}
})
}
error
Chrome 85.0.4183 (Windows 10.0.0) ERROR
Uncaught SyntaxError: Unexpected token 'export'
at assets/#zxing/library/esm/browser.js:2
Chrome 85.0.4183 (Windows 10.0.0) ERROR
Uncaught SyntaxError: Unexpected token 'export'
at assets/#zxing/library/esm/browser.js:2
JavaScript Test Case Exit Code 1
JavaScript Test Case Fails
I'm, trying to make use of zxing.js in my Angular.1x app. MY CI/CD getting failed due to this error. library is working properly inside the app. im facing this issue the moment I use gulp karmaRunDebug. So need experts advice to resolve this. I'm struggling to fix this problem for past two.
I've no clue what needs to be done as am completely new setting up gulp and karma test environment.
zxing -> library
Thanks
I'm facing the next situation with Cucumber in Protractor (With Webstorm)
When I try to run the only feature that I have, it displays the next message (I have already defined the steps in a class)
Undefined. Implement with the following snippet:
Given('I open the url {string}', function (string) {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
...
1 scenario (1 undefined)
4 steps (4 undefined)
0m00.000s
Process finished with exit code 1
This is my config file (conf.js)
exports.config = {
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl: 'https://www.afphabitat.cl/portalPrivado_FIXWeb/public/login.htm',
ignoreSynchronization: true,
getPageTimeout: 60000,
allScriptsTimeout: 50000,
defaultTimeoutInterval: 30000,
specs: ['features/*.feature'],
cucumberOpts: {
compiler: [],
require: ['step_defs/*.js'],
dryRun : false,
tags: ['#wip'],
monochrome: true,
strict: true,
plugin: "json",
format: 'json:reports/cucumber-report.json',
resultJsonOutputFile: 'reports/cucumber-report.json'
},
multiCapabilities:
[{
'browserName': 'chrome',
chromeOptions: {
binary: process.env.CHROME_BIN,
args: ['--no-sandbox', '--start-maximized']
}
},
{
'browserName': 'firefox',
args: ['--no-sandbox','--start-maximized']
}],
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
}
}
Next one is my step definition file (step_defs_Login.js)
import { Given, Then, When } from "cucumber";
import { browser, by, element, } from 'protractor';
Given('I open the url {string}', function (string) {
browser.get(string);
// callback();
});
When('proceed to enter my username as {string}', function (string1) {
let username = element(by.id('j_username_input')).clear();
username = element(by.id('j_username_input')).sendKeys(string1);
// callback();
});
When('proceed to enter my password as {string}', function (string2) {
let password = element(by.id('j_password')).clear();
password = element(by.id('j_password')).sendKeys(string2);
// callback();
});
Then('I have been logged in successfully', function () {
element(by.id('button')).click();
// callback();
});
Don't forget the JSON File (package.json)
{
"name": "package",
"version": "1.0.0",
"description": "First Protractor Cucumber project",
"main": "conf.js",
"scripts": {
"test": "cucumberjs"
},
"keywords": [
"TAE"
],
"author": "zzz",
"license": "ISC",
"devDependencies": {
"cucumber": "^5.1.0",
"selenium-webdriver": "^4.0.0-alpha.5"
},
"dependencies": {
"protractor": "latest"
}
}
I don't know if this is necessary or not, but this is my Hooks file (hooks.js)
let {defineSupportCode} = require('cucumber');
defineSupportCode (function ({After, Before}){
Before(function () {
// return this.driver.manage().window().maximize()
return this.browser.manage().window().maximize();
})
After(function () {
return this.driver.quit()
})
});
I have installed the next ones:
Protractor version 5.4.2
Node version 10.16.3
NPM 6.9.0
This is the project structure:
And this is the Run Configurations
Can anybody please help me with this???
Have you got the string you are passing in the feature file enclosed in "double quotes"?
I open the url "myUrl"
Try
require: ['../step_defs/*.js']
or
require: ['./step_defs/*.js']
In cucumberOpts object
Looks like you are using Webstrom to work on this cucumber framework. As I know, Webstrom will find the respective step definition for that step automatically. Coming to the issue,
1) Open your feature file and check that particular step is showing as implemented or not
2) Try to replace {string} with regular expression (.*) which will accept any type of data and check same step in feature file- step
Check both above cases
I'm trying to write some visual tests and running into the mentioned error with the protractor-image-comparison of version 2.0.1. Even though there is an update of the library I decided to stick to the older version since I experience some issues with the newest one as well.
My setup is:
//protractor.conf.js:
const { SpecReporter } = require('jasmine-spec-reporter');
const { join } = require('path');
const { ProtractorImageComparison } = require('protractor-image-comparison');
exports.config = {
allScriptsTimeout: 11000,
specs: ['./src/**/*-spec.ts'],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: [
// '--headless',
'--disable-gpu', '--window-size=1600,950', '--no-sandbox'],
},
},
SELENIUM_PROMISE_MANAGER: false,
directConnect: true,
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {
},
},
onPrepare() {
require('ts-node').register({
project: join(__dirname, './tsconfig.e2e.json'),
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
browser.protractorImageComparison = new ProtractorImageComparison({
baselineFolder: join(__dirname, '/src/resources/baseline/'),
screenshotPath: join(__dirname, '/src/tmp/'),
formatImageName: '{tag}',
autoSaveBaseline: false
});
},
};
I came across this issue today and apparently from version 3.0.1 this package now functions as a plugin and not a class which needs to be instantiated.
I managed to get it working adding the following code to my conf.js:
plugins: [
{
inline: require('protractor-image-comparison'),
// package: 'protractor-image-comparison' //protractor is installed globally so it is checking for plugin globally also
options: {
baselineFolder: './testArtifacts/screen-compare/baselines/',
screenshotPath: './testArtifacts/screen-compare/screenshots/',
formatImageName: `{tag}-{logName}-{width}x{height}`,
savePerInstance: true,
},
},
],
Note: For me protractor was installed globally so I needed this workaround using inline instead of package to get it searching for the plugin module locally.
I am getting a file table overflow issue while running the Karma tests, and I have no clue how to debug this.
karma.conf.js:
module.exports = function (config) {
config.set({
frameworks: ['jspm', 'jasmine'],
files: [
'node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
'node_modules/jasmine-async-sugar/jasmine-async-sugar.js'
],
jspm: {
config: 'jspm.conf.js',
loadFiles: ['src/app/app.js', 'src/app/**/*.spec.js'], //'src/app/**/!(*.e2e|*.po).js'
serveFiles: ['src/app/**/*.+(js|html|css|json)'] // *.{a,b,c} to *.+(a|b|c) https://github.com/karma-runner/karma/issues/1532
},
proxies: {
'/test/': '/base/test/',
'/src/app/': '/base/src/app/',
'/jspm_packages/': '/base/jspm_packages/'
},
//reporters: process.argv.slice(2).find((argv) => argv.includes('--nocoverage') || argv.includes('--no-coverage')) ? ['dots', 'junit'] : ['dots', 'junit', 'coverage'],
// use dots reporter, as Travis terminal does not support escaping sequences;
// when using Travis publish coverage to coveralls
reporters: coveralls ? ['dots', 'junit', 'coverage', 'coveralls'] : nocoverage ? ['dots'] : ['dots', 'junit', 'coverage'],
junitReporter: {
outputDir: 'test-reports/unit-test-report/',
suite: 'unit'
},
preprocessors: {
// source files, that you wanna generate coverage for - do not include tests or libraries
// (these files will be instrumented by Istanbul)
'src/**/!(*.spec|*.mock|*-mock|*.e2e|*.po|*.test).js': ['babel', 'coverage']
},
// transpile with babel since the coverage reporter throws error on ES6 syntax
babelPreprocessor: {
options: {
stage: 1,
sourceMap: 'inline'
}
},
coverageReporter: {
instrumenters: { isparta : require('isparta') },
instrumenter: {
'src/**/*.js': 'isparta'
},
dir: 'test-reports/coverage/',
subdir: normalizationBrowserName,
reporters: [
{type: 'html'}, // will generate html report
{type: 'json'}, // will generate json report file and this report is loaded to make sure failed coverage cause gulp to exit non-zero
{type: 'lcov'}, // will generate Icov report file and this report is published to coveralls
{type: 'text-summary'} // it does not generate any file but it will print coverage to console
]
},
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
browserNoActivityTimeout: 50000
});
function normalizationBrowserName(browser) {
return browser.toLowerCase().split(/[ /-]/)[0];
}
};
package.json:
"karma": "0.13.14",
"karma-jspm": "2.0.1",
"karma-jasmine": "0.3.6",
"karma-coverage": "douglasduteil/karma-coverage#next",
"karma-coveralls": "1.1.2",
"karma-ie-launcher": "0.2.0",
"karma-junit-reporter": "0.3.8",
"karma-chrome-launcher": "0.2.1",
"karma-safari-launcher": "0.1.1",
"karma-firefox-launcher": "0.1.6",
"karma-phantomjs-launcher": "0.2.1",
"karma-babel-preprocessor": "5.2.2"
test-unit.js:
gulp.task('karma', (cb) => {
// remove 'coverage' directory before each test
del.sync(path.test.testReports.coverage);
// run the karma test
const server = new Server({
configFile: path.test.config.karma,
browsers: BROWSERS.split(','),
singleRun: !argv.watch,
autoWatch: !!argv.watch
}, function(code) {
// make sure failed karma tests cause gulp to exit non-zero
if(code === 1) {
LOG(COLORS.red('Error: unit test failed '));
return process.exit(1);
}
cb();
});
server.start();
});
Error:
[08:44:36] 'karma' errored after 2.48 s [08:44:36] Error: ENFILE: file
table overflow, scandir '/Users/Abhi/Documents/projects/test/src/app'
at Error (native) at Object.fs.readdirSync (fs.js:808:18) at
GlobSync._readdir
(/Users/Abhi/Documents/projects/test/node_modules/karma/node_modules/glob/sync.js:275:41)
at GlobSync._processGlobStar
(/Users/Abhi/Documents/projects/test/node_modules/karma/node_modules/glob/sync.js:330:22)
at GlobSync._process
(/Users/Abhi/Documents/projects/test/node_modules/karma/node_modules/glob/sync.js:128:10)
at new GlobSync
(/Users/Abhi/Documents/projects/test/node_modules/karma/node_modules/glob/sync.js:46:10)
at new Glob
(/Users/Abhi/Documents/projects/test/node_modules/karma/node_modules/glob/glob.js:111:12)
at
/Users/Abhi/Documents/projects/test/node_modules/karma/lib/file-list.js:161:14
at Array.map (native) at [object Object].List._refresh
(/Users/Abhi/Documents/projects/test/node_modules/karma/lib/file-list.js:153:37)
at [object Object].List.refresh
(/Users/Abhi/Documents/projects/test/node_modules/karma/lib/file-list.js:252:27)
at [object Object].Server._start
(/Users/Abhi/Documents/projects/test/node_modules/karma/lib/server.js:177:12)
at [object Object].invoke
(/Users/Abhi/Documents/projects/test/node_modules/karma/node_modules/di/lib/injector.js:75:15)
at [object Object].Server.start
(/Users/Abhi/Documents/projects/test/node_modules/karma/lib/server.js:101:18)
at Gulp.
(/Users/Abhi/Documents/projects/test/gulp/tasks/test-unit.js:53:12) at
module.exports
(/Users/Abhi/Documents/projects/test/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask
(/Users/Abhi/Documents/projects/test/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep
(/Users/Abhi/Documents/projects/test/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start
(/Users/Abhi/Documents/projects/test/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
at
/Users/Abhi/Documents/projects/test/node_modules/gulp/bin/gulp.js:129:20
at nextTickCallbackWith0Args (node.js:419:9) at process._tickCallback
(node.js:348:13)
Karma Issue Tracker: https://github.com/karma-runner/karma/issues/1979
Abhi,
I spent a good afternoon on this and found a workaround, to what i have admit is a best guess issue that i have zero idea WHY is happening.
My issue was with the globs inside of serveFiles and loadFiles in the Karma config. To fix i did my own globbing using glob.sync to generate the arrays as i needed and this WORKED!
module.exports = function(config) {
var options = {cwd:"www"};
var glob = require("glob");
var filesToServe = glob.sync("./src/**/*.#(js|ts|css|scss|html)", options);
var specsToLoad = glob.sync("./src/**/*.#(spec.ts)", options).map(function(file){
return file.substr(2);
});
config.set({
basePath: 'www',
frameworks: ['jspm', 'jasmine'],
jspm: {
config: './test/config.js',
loadFiles: ['test/boot.ts'].concat(specsToLoad),
serveFiles: filesToServe,
},
files: [
'http://cdn.auth0.com/js/lock-8.2.min.js'
],
proxies: {
'/src/': '/base/src/',
'/.test/': '/base/.test/'
},
port: 9876,
logLevel: config.LOG_DISABLE,
colors: true,
autoWatch: true,
browsers: ['Chrome'],
plugins: [
'karma-jspm',
'karma-jasmine',
'karma-chrome-launcher',
'karma-spec-reporter'
],
reporters: ['spec'],
singleRun: true
});
};
The filesToServe and specsToLoad are treated slightly differently, i needed to remove the ./ from the files to load as it interferes with SystemJS's loading internally (this can be recognised by it trying to load a .ts.js file). Also i've got my work in a sub folder, 'www' which you might not need e.g. remove the cwd.
Hopefully you can see what i've done here and it helps you find a workaround. If anyone knows why something like glob is breaking i'd love to know.
To prove it was glob i did a simple test, using
require(glob)("src/**/*",function(file){ console.log(file); });
This triggered the same error, clearly NOTHING to do with too many files or a file table issue. If this pops up in other places, i'm going to have to clean install the OS again i think. However in my code base i use globs in other places, without any issue. I had wondered if it perhaps was the difference between using the 'sync' version of the process...
A day of wading through options to end up here... i had hoped to find a better answer.
K