Failed loading config.ts due to import protractor - node.js

I am trying to start a new protractor project to test an angular site. I installed node.js, typescript, protractor globally and jasmine. I go to the project folder and do webdriver-manager update. Then I do webdriver-manager start. I also build the config.ts using tsc config.ts. Everything works fine until i try protractor config.ts. Here i will provide my config.ts and my package.json.
{
"name": "protractortests",
"version": "1.0.0",
"description": "Automated tests for a game platform",
"main": "index.js",
"dependencies": {
"#types/jasmine": "^3.3.12",
"#types/node": "^12.0.2",
"jasmine": "^3.4.0",
"protractor": "^5.4.2"
},
"devDependencies": {},
"scripts": {
"test": "protractor config.ts"
}
and my config.ts:
import { ProtractorBrowser, Config } from "protractor";
export let config: Config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {
'browserName': 'chrome'
},
framework: 'jasmine',
specs: ['./FirstSpec.ts'],
jasmineNodeOpts: {
defaultTimeoutInterval: 90000
},
onPrepare: () => {
let globals = require('protractor/built');
let browser = globals.browser;
browser.manage().window().maximize();
browser.manage().timeouts().implicitlyWait(5000);
}
}
E/configParser - Error code: 105
[11:40:53] E/configParser - Error message: failed loading configuration file config.ts
[11:40:53] E/configParser - C:\Users\Victor\Documents\ProtractorTests\config.ts:1
(function (exports, require, module, __filename, __dirname) { import { ProtractorBrowser, Config } from "protractor";
^
SyntaxError: Unexpected token {
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
npm ERR! Test failed. See above for more details.

By referring to example at link https://github.com/angular/protractor/tree/5.4.1/exampleTypescript
You don't need to import ProtractorBrowser. You can work with browser directly with object Browser.

Commenters pointed out that you can't give Protractor a config file in native Typescript, and need to compile it to config.js then pass that. There's really no point in writing the file in Typescript at all, it just adds an extra step that provides no value to you. If you want editor autocomplete, you can decorate your JS with type annotations:
const { join } = require("path");
const { register } = require("ts-node");
const { SpecReporter, StacktraceOption } = require("jasmine-spec-reporter");
/** #type {import("protractor").Config} */
const config = {
directConnect: true,
baseUrl: "http://localhost:8080",
framework: "jasmine",
noGlobals: true,
specs: [ "./src/**/*.e2e.ts" ],
onPrepare() {
register({
project: join(__dirname, "./tsconfig.json")
});
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: StacktraceOption.PRETTY
}
}));
}
};
module.exports = { config };
I adapted my config from this excellent example.

Related

ts-node cannot find npm module discord-api-types

When attempting to run discord.js file deploy-commands.ts with the command ts-node deploy-commands.ts ts-node produces the following error:
Error: Cannot find module 'discord.js/node_modules/discord-api-types'
Require stack:
- /Users/Cameron/discord.js/discordjs-guides/deploy-commands.ts
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/usr/local/lib/node_modules/ts-node/node_modules/#cspotcode/source-map-support/source-map-support.js:679:30)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/Cameron/discord.js/discordjs-guides/deploy-commands.ts:4:1)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1455:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1458:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/Users/Cameron/discord.js/discordjs-guides/deploy-commands.ts' ]
}
Despite discord-api-types appearing both in the node-modules folder and in package.json. The error is consistently reproduced after running npm install discord-api-types and npm resoding discord-api-types is up-to-date.
Package.json dependencies:
"dependencies": {
"#discordjs/builders": "^0.12.0",
"#discordjs/rest": "^0.3.0",
"discord-api-types": "^0.29.0",
"discord.js": "^13.6.0",
"dotenv": "^16.0.0",
"nodemon": "^2.0.15",
"ts-node": "^10.7.0"
}
deploy-commands.ts:
import { SlashCommandBuilder } from "#discordjs/builders";
import { REST } from "#discordjs/rest";
import { version } from "discord.js";
import { Routes } from "discord.js/node_modules/discord-api-types";
const { token, guildID, clientID } = require('./process.json')
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong.'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info.'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info.'),
]
.map(commands => JSON)
const rest = new REST({version: '9'}).setToken(token)
rest.put(Routes.applicationCommand(clientID, guildID), {body: { commands }})
.then(() => {
console.log('Successfully registered application commands')
})
.catch(console.error)
I think you need to change this code line:
import { Routes } from "discord.js/node_modules/discord-api-types";
To its version using because of this:
const rest = new REST({version: '9'}).setToken(token)
So you need to define the version you use, try changing your import to
import { Routes } from "discord-api-types/v9";
As I tried to my testing slash command files, you can do this kind of line too:
import { Routes } from "discord.js/node_modules/discord-api-types/v9";
I'm not using .ts so might not work but give it a shot

How to lint a typescript types file?

are there any ways to lint or otherwise debug a types file?
I have a index.d.ts file of all my types, but it seems to crash my app at startup.
using tsc with some basic options works fine
using tslint works fine.
but when running with the webpack compiler I get the following error.
the file contents are a lot but basically like the below.
I had some issues with exporting enums before but basically not getting any actual errors I can understand.
// we SEND to Boto
export enum MsgTypeOut {
TEXT = 0,
IMAGE = 1,
URL_LINK = 2,
FILE = 3,
}
export interface BotoTextMsg {
chatId: string
messageType: MsgTypeOut.TEXT
token?: string
payload: {
text: string
}
}
nodemon:watch early exit on watch, still watching (1) +14s
/Users/dc/dev/tix/recobot/stack/backend/server.js:2663
throw new Error("Module build failed: Error: Typescript emitted no output for /Users/dc/dev/tix/recobot/stack/shared/typezoo/index.d.ts.\n at successLoader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:47:15)\n at Object.loader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:29:12)");
^
Error: Module build failed: Error: Typescript emitted no output for /Users/dc/dev/tix/recobot/stack/shared/typezoo/index.d.ts.
at successLoader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:47:15)
at Object.loader (/Users/dc/dev/tix/recobot/stack/backend/node_modules/ts-loader/dist/index.js:29:12)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:2663:7)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.defineProperty.value (/Users/dc/dev/tix/recobot/stack/backend/server.js:2551:19)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:867:16)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:1306:18)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:1343:30)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.__awaiter (/Users/dc/dev/tix/recobot/stack/backend/server.js:1028:15)
at __webpack_require__ (/Users/dc/dev/tix/recobot/stack/backend/server.js:20:30)
at Object.defineProperty.value (/Users/dc/dev/tix/recobot/stack/backend/server.js:63:18)
at Object.<anonymous> (/Users/dc/dev/tix/recobot/stack/backend/server.js:66:10)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
[nodemon] app crashed - waiting for file changes before starting...
webpack config is pretty much vanilla based on create-react-app.
const fs = require("fs")
// const path = require("path")
const NodemonPlugin = require("nodemon-webpack-plugin");
const nodeModules = {};
fs.readdirSync("node_modules")
.filter(function (x) {
return [".bin"].indexOf(x) === -1;
})
.forEach(function (mod) {
nodeModules[mod] = "commonjs " + mod;
});
module.exports = {
entry: "./server/server.ts",
output: {
filename: "server.js",
// path: path.join(__dirname, "/build"),
},
externals: nodeModules,
// needed to fix https://github.com/webpack/webpack/issues/1599
node: {
__dirname: true
},
module: {
loaders: [
{
loader: "ts-loader",
test: /\.tsx?$/,
},
],
},
plugins: [new NodemonPlugin()],
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
},
target: "node",
};
For anyone watching, the error is related to importing enums.
You can export an enum from a types.d.ts file... but it won't import and blows up in this weird way.
https://lukasbehal.com/2017-05-22-enums-in-declaration-files/
How to refer to Typescript enum in d.ts file, when using AMD?

cannot find protractor-result folder 'protractor-html-screenshot-reporter'

I'm trying to generate reports in Protractor and i followed this tutorial to do that.
Here is my conf.js file.
var HtmlReporter = require('protractor-html-screenshot-reporter');
var reporter = new HtmlReporter({
baseDirectory: 'D:/My Work/Protractor/Financial/protractor-result', // a location to store screen shots.
docTitle: 'Protractor Demo Reporter',
docName: 'protractor-demo-tests-report.html'
});
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['invoice.js'],
capabilities: {
browserName: 'chrome',
},
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
},
onPrepare: function() {
jasmine.getEnv().addReporter(reporter);
}
}
I tried run this using command protractor conf.js and there's no folder generated containing test results. If I use command, protractor specs\configurations.js following error occurs.
ERROR - failed loading configuration file specs/conf.js
C:\Users\Manuli\AppData\Roaming\npm\node_modules\protractor\lib\configParser.js:
204
throw e;
^
Error: Cannot find module 'D:\My Work\Protractor\Financial\specs\conf.js'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at ConfigParser.addFileConfig (C:\Users\Manuli\AppData\Roaming\npm\node_modu
les\protractor\lib\configParser.js:195:22)
at Object.init (C:\Users\Manuli\AppData\Roaming\npm\node_modules\protractor\
lib\launcher.js:103:18)
at Object.<anonymous> (C:\Users\Manuli\AppData\Roaming\npm\node_modules\prot
ractor\lib\cli.js:140:23)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
Why can't I generate reports?
Thanks in advance. :)
I changesd my conf.js as this.
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporter = new HtmlScreenshotReporter({
dest: 'D:/My Work/Protractor/Financial/screenshots',
filename: 'my-report.html'
});
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['invoice.js'],
capabilities: {
browserName: 'chrome',
},
// Setup the report before any tests start
beforeLaunch: function() {
return new Promise(function(resolve){
reporter.beforeLaunch(resolve);
});
},
// Assign the test reporter to each running instance
onPrepare: function() {
jasmine.getEnv().addReporter(reporter);
},
// Close the report after all tests finish
afterLaunch: function(exitCode) {
return new Promise(function(resolve){
reporter.afterLaunch(resolve.bind(this, exitCode));
});
}
}
Then I used npm install protractor-jasmine2-screenshot-reporter --save-dev command to install npm.
Working now. :)

Webstorm Unexpected Token export

I am having an "Unexpected token export" issue in Webstorm that has not been solved by the other StackOverflow posts. Essentially I am trying to use the import/export module functionality with the package.json and bar.js code below. I am using Node.js 5x, Babel 6, and I have a File Watcher setup to do the Babel transforms on the fly.
The code should speak for itself, and I appreciate any thoughts on how to resolve it. Again, I have tried the other StackOverflow suggestions with no luck at this point.
//bar.js
'use strict';
export class Bar{
constructor(){
this.tempish = 'allo';
}
}
//bar-compiled.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Bar = exports.Bar = function Bar() {
_classCallCheck(this, Bar);
this.tempish = 'allo';
};
//# sourceMappingURL=bar-compiled.js.map
//index.js
'use strict';
import {Bar} from './bar'
console.log('This is a test.');
//index-compiled.js
'use strict';
var _bar = require('./bar');
console.log('This is a test.');
//# sourceMappingURL=index-compiled.js.map
//package.json
{
"name": "npt-test",
"version": "1.0.0",
"description": "",
"main": "index-compiled.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^6.3.26",
"babel-cli": "^6.4.5",
"babel-core": "^6.4.5",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.3.13",
"babel-preset-stage-0": "^6.3.13"
}
}
//.babelrc
{
"presets": ["es2015", "stage-0", "stage-1"],
"plugins": ["babel-plugin-transform-decorators-legacy"]
}
//Error on debug, I am running against the index-compiled.js during debug
C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe"
"C:\Program Files\nodejs\node.exe" --debug-brk=45287 --nolazy index-compiled.js
Debugger listening on port 45287
[MYPROJECTDIR]\bar.js:3
export class Bar{
^^^^^^
SyntaxError: Unexpected token export
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:404:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> ([MYPROJECTDIR]\index-compiled.js:3:12)
at Module._compile (module.js:397:26)
at Object.Module._extensions..js (module.js:404:10)
Process finished with exit code 1
what does your index-compiled.js code look like? seems it requires original bar.js rather than bar-compiled.js. Node.js can't natively execute ES6 code, thus the errors.
I'd recommend configuring the compiler to output transpiled code into a separate directory to avoid using 'compiled' postfix. Please see the following link for instructions on setting up Babel 6 with WebStorm: http://mcculloughwebservices.com/2015/12/10/webstorm-babel-6-plugin/

Setting up TypeScript for node by using module=system is not working

I tried to setup a restify project using typescript.
After various tries I was able to create a working version by using "module: commonjs" in the tsconfig.json
I'd prefer to use system - but I wasn't able to set it up with systemjs
boot.ts
import {AppServer} from './app';
var _appServer = new AppServer();
tsconfig.json
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}
app.ts
/// <reference path="typings/restify/restify.d.ts" />
import {Server, Response, Request, createServer} from 'restify';
export class AppServer {
private server: Server;
constructor() {
this.init();
}
init() {
this.server = createServer();
this.server.get('/hello/:name', this.respond);
this.server.listen(8080, () => {
console.log('%s listening at %s', this.server.name, this.server.url);
});
}
respond(req: Request, res: Response, next: Function) {
res.send('hello ' + req.params.name);
next();
}
}
using
"module": "system"
in the tsconfig.json, I get the following output (even with import System = require('systemjs')in the boot.ts):
➜ server git:(master) ✗ npm run server
> server#1.0.0 server /Users/maquh/Development/02_Backgular/server
> node boot.js
/Users/maquh/Development/02_Backgular/server/boot.js:1
(function (exports, require, module, __filename, __dirname) { System.register(['./app'], function(exports_1) {
^
ReferenceError: System is not defined
at Object.<anonymous> (/Users/maquh/Development/02_Backgular/server/boot.js:1:63)
at Module._compile (module.js:425:26)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3
Transpiled boot.js
System.register(['./app'], function(exports_1) {
var app_1;
var _appServer;
return {
setters:[
function (app_1_1) {
app_1 = app_1_1;
}],
execute: function() {
//System.import('./app.ts').
_appServer = new app_1.AppServer();
}
}
});
//# sourceMappingURL=boot.js.map
UPDATE:
I also tried another alternative version of boot.ts
var System = require('systemjs');
System.transpiler = 'ts';
System.import('./app.js').then(function(m) {
console.log(m);
}, function(err) {
console.error(err);
});
those leads to the following error:
[Error: ENOENT: no such file or directory, open '/Users/markusbellgardt/Development/02_Backgular/server/restify']
System uses ES6 module loaders which nodejs (to my knowledge) does not currently support, your initial use case was right where you were outputting to commonjs. If you want to use the ES6 style module resolution within node you will need to tell node how to load it such as:
https://www.npmjs.com/package/es6-module-loader
I use typescript in node fine but I use commonjs, I have used system in the browser before and it works fine when you have ES6 module loaders available such as SystemJs (JSPM).

Resources