mocha Unknown file extension ".ts" - node.js

Trying to get this to work from the following example
In my mocharc.json:
{
"extension": ["ts"],
"spec": "test/unit/**/*.spec.ts",
"require": "ts-node/register"
}
in package.json:
"scripts": {
"tstest": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha",
...
"#types/mocha": "^10.0.0",
"mocha": "^9.2.0",
"ts-node": "^10.9.1",
"typescript": "^4.8.4"
Running tstest gives me:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for project/test/unit/create.spec.ts
at new NodeError (node:internal/errors:393:5)
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
at defaultLoad (node:internal/modules/esm/load:81:20)
at nextLoad (node:internal/modules/esm/loader:163:28)
at ESMLoader.load (node:internal/modules/esm/loader:605:26)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
at new ModuleJob (node:internal/modules/esm/module_job:63:26)
at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:480:17)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
at async importModuleDynamicallyWrapper (node:internal/vm/module:438:15)
at async formattedImport (project/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
at async Object.exports.requireOrImport (project/node_modules/mocha/lib/nodejs/esm-utils.js:48:32)
at async Object.exports.loadFilesAsync (project/node_modules/mocha/lib/nodejs/esm-utils.js:103:20)
at async singleRun (project/node_modules/mocha/lib/cli/run-helpers.js:125:3)
at async Object.exports.handler (project/node_modules/mocha/lib/cli/run.js:374:5)
and create.spec.ts is:
import { expect } from 'chai'
describe('Happy to get this to work', () => {
it('ts test', async () => {
expect(true).to.be.equal(false)// yes it should fail
})
})
I cloned the example and put the tsconfig from my project in there and it worked on the sample but not in my project. Can't figure out what I'm missing here.
When I use ts-node and typescript versions from the package.json in the example I get error Error: Debug Failure. False expression: Non-string value passed to ts.resolveTypeReferenceDirective,.

Related

Electron with strapi, Cannot find module package.json

I built an application using strapi, i am trying to package it inside electron using electron-builder.
The packaging is done well, but when i start the app, it shows this message
PS E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked>
(node:13196) UnhandledPromiseRejectionWarning: Error: Cannot find module 'E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\package.json'
Require stack:
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\index.js
- E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\index.js
-
at Module._resolveFilename (internal/modules/cjs/loader.js:797:17)
at Function.o._resolveFilename (electron/js2c/browser_init.js:281:679)
at Module._load (internal/modules/cjs/loader.js:690:27)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at new Strapi (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js:94:21)
at module.exports (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\node_modules\strapi\lib\Strapi.js:564:18)
at createWindow (E:\Development\DentalSystem\dentalBE_test\dist\win-unpacked\resources\app\index.js:23:5)
(node:13196) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13196) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
What seems to be the problem is that my application is looking to package.json file inside the root folder (directly relative to the exe file), while it exist inside the (app) folder with all other resources of the system.
this is my package.json file
{
"name": "DentalSys",
"main": "./index.js",
"version": "0.2.0",
"description": "Dental Clinic Management System",
"productName": "DentalSys",
"build": {
"appId": "com.kldoon.dentalSys",
"asar": false
},
"scripts": {
"develop": "strapi develop",
"strapi-start": "strapi start",
"strapi-prod": "cross-env NODE_ENV=production npm start",
"strapi-build": "strapi build",
.....
},
"devDependencies": {
"concurrently": "^5.1.0",
"electron": "^9.1.2",
"electron-builder": "^22.4.1",
......
},
"dependencies": {
"knex": "0.20.13",
"moment": "^2.27.0",
"sqlite3": "^4.1.1",
"strapi": "3.0.0-beta.17.5",
.......
}
And this is my electron (index.js) file
const { app, BrowserWindow, Menu, dialog } = require('electron')
const path = require("path");
const strapi = require('strapi');
//const { exec } = require("child_process");
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
maximizable: true,
title: "Dental System",
webPreferences: {
nodeIntegration: true
}
})
win.maximize();
strapi().start().then(() => {
win.loadURL('http://localhost:49862/');
}).catch((e) => {
console.log(e);
});
win.on('closed', () => {
app.quit();
})
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
I tried multiple solutions but none work, i hope someone can help with it.
Thanks in advance.
It turned out to be easy fix, with dir option of strapi constructor
strapi({
dir: __dirname + '/' ///<==== add this
}).start().then(() => {
win.loadURL('http://localhost:1337/');
}).catch((e) => {
dialog.showMessageBox(win, { message: JSON.stringify(e) });
console.log(e);
});

Unhandled error while running jest-puppeteer test

I am trying to set up testing for my puppeteer project. I was following a basic guide and the test passes but there is 2 console errors in the terminal.
The error doesn't show up when using https://google.com or https://youtube.com. So it looks like it could be a thing with the specific site?
console.error
Unhandled error
at process.uncaught (node_modules/jest-jasmine2/build/jasmine/Env.js:248:21)
at handler (node_modules/jest-environment-puppeteer/lib/PuppeteerEnvironment.js:17:11)
at map (node_modules/mitt/src/index.ts:74:75)
at Array.map (<anonymous>)
at Object.emit (node_modules/mitt/src/index.ts:74:56)
at Page.emit (node_modules/puppeteer/lib/EventEmitter.js:72:22)
console.error
at process.uncaught (node_modules/jest-jasmine2/build/jasmine/Env.js:249:21)
at handler (node_modules/jest-environment-puppeteer/lib/PuppeteerEnvironment.js:17:11)
at map (node_modules/mitt/src/index.ts:74:75)
at Array.map (<anonymous>)
at Object.emit (node_modules/mitt/src/index.ts:74:56)
at Page.emit (node_modules/puppeteer/lib/EventEmitter.js:72:22)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.613 s
Ran all test suites.
Here is my code
describe('NCAA Home', () => {
beforeAll(async () => {
await page.goto('http://stats.ncaa.org/rankings/change_sport_year_div');
});
it('should be titled "NCAA Statistics"', async () => {
await expect(page.title()).resolves.toMatch('NCAA Statistics');
});
});
Here is my jest.config.js
module.exports = {
preset: "jest-puppeteer",
testMatch: [
"**/test/**/*.test.js"
],
verbose: true
}
package.json
{
"name": "stackoverflow",
"version": "1.0.0",
"description": "",
"main": "index.js",
"jest": {
"preset": "jest-puppeteer"
},
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^26.1.0",
"jest-puppeteer": "^4.4.0"
},
"dependencies": {
"puppeteer": "^5.1.0"
}
}
All of the things I have come across have mentioned an issue with async/await but anything I have tried produces the same, if not, more errors. I have made a new project with these files and I am getting the same error
The error is from the website itself. Check the console of the website. Hence for a websites like google.com or youtube.com, it works without any errors.
I have created clean repo which reproduces issue.
https://github.com/sergtimosh/jest-puppeteer-issue-reproduction.git
clone repository
npm i
npm test test.spec.js
or
HEADLESS=false npm test test.spec.js
A workaround is to create incognito browser context in jest-environment.js.
Just uncomment two lines in this file and tests are passing with no issues. But problem is still here if you need to share browser context between test suites(files).
const PuppeteerEnvironment = require('jest-environment-puppeteer');
class JestEnvironment extends PuppeteerEnvironment {
async setup() {
await super.setup()
//to fix issue uncomment next two lines
// const incognitoContext = await this.global.browser.createIncognitoBrowserContext()
// this.global.page = await incognitoContext.newPage()
}
async teardown() {
await super.teardown()
}
}
module.exports = JestEnvironment;

Failed loading config.ts due to import protractor

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.

Testing Keystone and Mongoose with Jest

I am implementing unit testing in a project with Keystone but it always throws an error at testing:
an all test suites.
/Project/node_modules/mongodb/lib/mongo_client.js:433
throw err
^
TypeError: require(...) is not a function
at /Project/node_modules/keystone/lib/core/start.js:64:44
at /Project/node_modules/async/dist/async.js:3880:24
at eachOfArrayLike (/Project/node_modules/async/dist/async.js:1069:9)
at eachOf (/Project/node_modules/async/dist/async.js:1117:5)
at _parallel (/Project/node_modules/async/dist/async.js:3879:5)
at Object.parallelLimit [as parallel] (/Project/node_modules/async/dist/async.js:3962:5)
at /Project/node_modules/keystone/lib/core/start.js:60:9
at connected (/Project/node_modules/keystone/lib/core/openDatabaseConnection.js:78:5)
at NativeConnection.<anonymous> (/Project/node_modules/keystone/lib/core/openDatabaseConnection.js:85:4)
at Object.onceWrapper (events.js:273:13)
at NativeConnection.emit (events.js:182:13)
at /Project/node_modules/mongoose/lib/connection.js:860:13
at connectCallback (/Project/node_modules/mongodb/lib/mongo_client.js:527:5)
at /Project/node_modules/mongodb/lib/mongo_client.js:430:11
at process._tickCallback (internal/process/next_tick.js:61:11)
npm ERR! Test failed. See above for more details.
I already tried using "import { init, start, mongoose } from 'keystone';" instead, and using jest async() and await. I run too "jest --clearCache". Jest version: "jest": "^24.3.1"
My .babelrc:
{
"presets": [
["#babel/preset-env",
{"targets": {
"node": "current"
}}
],
"#babel/preset-react"
]
}
test.js:
const Keystone = require('keystone');
beforeAll( done => {
Keystone.init({
'name': 'Keystone CMS',
'cookie secret': 'My_Biscuit',
});
Keystone.start();
done();
})
describe('Test Keystone CMS own features', () => {
test('Keystone connects to MongoDB', (done) => {
expect(Keystone.mongoose.connections._listening).toBeTruthy;
done();
});
});
I will then expand it to test mongoose
It seems, that it is not really possible at the moment:
https://github.com/keystonejs/keystone/issues/3564

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/

Resources