I'm getting the following error:
Jest encountered an unexpected token ....
} catch {
^
I'm assuming that I need babel to transform the files that i'm importing but I don't understand how jest/babel are wired up together. How do I get it to transform my imported file so I can have try/catch.
I have the following code:
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
package.json
{
"name": "tests",
"scripts": {
"test": "jest"
},
"author": "jonny-b",
"dependencies": {
"jest": "^24.8.0",
"ruby-script": "^1.0.3"
}
}
index.js
class Collection extends Array {
constructor(array) {
super(array.length);
Object.assign(this, array);
}
//....
drill(...indices) {
if (this[indices] === null) return null;
if (indices.length === 1) return this[indices];
let indexes = indices.splice(indices[0]);
try {
let collection = new Collection(this[indices[0]]);
return collection.drill(...indexes);
} catch {
throw `${typeof (this[indices[0]])}`
}
}
}
script.test.js
let Collection = require('<path to file>/index.js');
describe('ruby-script', () => {
it('should error if called on a non collection return value', () => {
let collection = new Collection([1, [2, [3, [4, [5, [6, [7]]]]]]]);
expect(collection.dig(1)).toEqual(true)
})
}
Related
I am integrating Vite SSR to existing vue project. I copied vite configuration from SSR playground project and bumped ionic version to 6 because of dynamic loading issue from stencil.
After upgrading, it isn't compiling, showing this error.
12:03:15 AM [vite] Error when evaluating SSR module /src/components/ImportType.vue:
/data/Work/ssr-vue/node_modules/#ionic/core/components/ion-accordion.js:4
import { proxyCustomElement, HTMLElement, h, Host } from '#stencil/core/internal/client';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Here is my vite.config.js file
const vuePlugin = require('#vitejs/plugin-vue')
const vueJsx = require('#vitejs/plugin-vue-jsx')
const virtualFile = '#virtual-file'
const virtualId = '\0' + virtualFile
const nestedVirtualFile = '#nested-virtual-file'
const nestedVirtualId = '\0' + nestedVirtualFile
/**
* #type {import('vite').UserConfig}
*/
module.exports = {
plugins: [
vuePlugin(),
vueJsx(),
{
name: 'virtual',
resolveId(id) {
if (id === '#foo') {
return id
}
},
load(id) {
if (id === '#foo') {
return `export default { msg: 'hi' }`
}
}
},
{
name: 'virtual-module',
resolveId(id) {
if (id === virtualFile) {
return virtualId
} else if (id === nestedVirtualFile) {
return nestedVirtualId
}
},
load(id) {
if (id === virtualId) {
return `export { msg } from "#nested-virtual-file";`
} else if (id === nestedVirtualId) {
return `export const msg = "[success] from conventional virtual file"`
}
}
}
],
ssr: {
external: ["npm: #ionic/vue"]
},
build: {
minify: false
}
}
Please help me.
I have the below config in my test runner and trying to merge all the mochaweasome.html file as single mocha file.
Runner.js
async function testRunner(fixture) {
return cypress.run({
config: {
"reporter": "mochawesome",
"reporterOptions": {
"reportFilename": "sample" + `${fixture}`,
"reportDir":"./cypress/reports/",
"charts": true,
"overwrite": false,
"html": true,
"json": true
}
},
env: {
testcaseID: `${fixture}`,
},
spec: './cypress/integration/' + `${param.getSpec()}` + ".spec.js",
});
}
TestRunner.js:
const testRunner = require("./Runner.js");
const options = {
files: [
'./cypress/reports/*.html',
],
}
async function generateReport(options) {
return merge(options).then(report => marge.create(report, options))
}
async function runner(dataSet) {
for (let i = 0; i < dataSet.length; i += 1) {
await setTimeout[Object.getOwnPropertySymbols(setTimeout)[0]](10000);
try {
await testRunner(dataSet[i]).then((result) => {
console.log(JSON.stringify(result, null, " "));
generateReport(options);
if (result.runs[0].stats.failures === 1) {
retry.push(result.config.env.testcaseID);
}
},
error => {
generateReport(options);
console.error(error);
process.exit(1);
});
}
catch (err) {
process.exit(1);
}
}
}
Test Report is created like below:
But It's not merged as single report as per the code.
Can someone help me to fix this. I just want single mochaweasome_final report which contains all the result in a single .html file.
Updated:
Used cypress-mochawesome-reporter and followed all the steps. But still the report is not merged. How can I merge all the 5 html files into single one.
Output:
First, you have to install mocha reporter using npm i cypress-mochawesome-reporter command.
and then you have to put this import in support/index.js
import 'cypress-mochawesome-reporter/register';
And import this line in plugin/index.js
module.exports = (on, config) => {
require('cypress-mochawesome-reporter/plugin')(on);
};
And then in your cypress.json file
"reporter": "cypress-mochawesome-reporter",
"reporterOptions": {
"reportDir": "cypress/reports",
"charts": true,
"overwrite": false,
"html": false,
"json": true,
"reportPageTitle": "My Test Suite",
"embeddedScreenshots": true,
"inlineAssets": true
Reference: https://www.npmjs.com/package/cypress-mochawesome-reporter
I have a project written for browser using AMD modules, now I need to run the same code in nodejs, so I need to rewrite each file into using CommonJs modules instead. I tried webpack, but it gives me a bundle which I don't need. All I want is to keep my files like they are but rewrite define(.. imports to require(..)
thank to Felix Kling's advice i wrote the following transformer in typescript
import { FileInfo, API, Options } from 'jscodeshift';
import { resolve, normalize, relative } from 'path';
export default function transformer(file: FileInfo, api: API, options: Options) {
const { j } = api;
return j(file.source)
.find(j.ExpressionStatement, { expression: { callee: { name: 'define' } } })
.replaceWith(({ node }) => {
const { expression: defineCallExpression } = node;
if (defineCallExpression.type !== 'CallExpression') return crash('No call to define function of AMD.');
const [moduleLocationsArray, callback] = defineCallExpression.arguments;
if (callback.type !== 'FunctionExpression') return;
if (moduleLocationsArray.type !== 'ArrayExpression') return;
const imports = moduleLocationsArray.elements.map((element, index) => {
if (element === null) return crash('Module name skipped.');
if (element.type !== 'Literal') return crash('Module name is not a literal');
const param = callback.params[index];
if (param.type !== 'Identifier') return crash('Module parameter is not an identifier.');
return {
location: element.value as string,
name: param.name,
};
}).filter(pair => shouldKeepModule(pair.location));
const filePath = normalize(resolve(__dirname, file.path));
const baseDir = normalize(resolve(__dirname, options.where));
const importStatements = imports.map(({name, location}) => {
const modulePath = normalize(resolve(baseDir, location));
const relativeModuleName = slashings(relative(filePath, modulePath));
const text = `const ${name} = require('${relativeModuleName}');`;
const statement = api.j(text, options);
return statement;
});
const statementsBefore = callback.body.body;
const statementsAfter = [...importStatements, ...statementsBefore];
return statementsAfter;
})
.toSource();
}
function shouldKeepModule(location: string): boolean {
return location !== 'module' && location !== 'exports' && location !== 'require';
}
function crash(message: string): never { throw new Error(message); }
function slashings(text: string): string { return text.replace(/\\/g, '/'); }
with the following tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"strict": true,
"target": "es6",
"module": "commonjs",
"lib": ["es6"],
"types": ["node", "jscodeshift"],
"outDir": "../../node_modules/amd-to-commonjs"
}
}
with the following package.json
{
"private": true,
"devDependencies": {
"#types/node": "7.0.4",
"#types/jscodeshift": "0.6.0",
"jscodeshift": "0.6.3",
"typescript": "3.4.0-dev.20190227"
}
}
built by the following command
npm install
node ../../node_modules/typescript/bin/tsc --project ./
and run by the following command
node ../../node_modules/jscodeshift/bin/jscodeshift.js --transform=../../node_modules/amd-to-commonjs/transformer.js --where=../../scripts/built ../../scripts/built
I'm using babel-preset-env (Babel 6) and I can't find out how to disable the "promise" transpilation.
I tried to use:
{
"presets": [
[
"env",
{
"exclude": ["transform-async-to-generator", "es6.promise"]
}
]
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
[
"fast-async",
{
"spec": true,
"compiler": { "promises": true, "generators": false }
}
]
]
}
and, while it doesn't throws any errors (unlike it happens when an invalid option is passed), it still transpiles promises into runtimeGenerator functions.
How can I make so that babel-preset-env will transpile everything but preserve promises?
Okay, now with the actual .babelrc and mention of fast-async and so on... A .babelrc like this seems to be enough to use fast-async instead of regenerator-runtime etc.
{
"presets": [
[
"env",
{
"exclude": ["babel-plugin-transform-async-to-generator", "babel-plugin-transform-regenerator"]
}
]
],
"plugins": [
[
"fast-async",
{
"spec": true,
"compiler": { "promises": true, "generators": false }
}
]
]
}
Promises shouldn't be transpiled to anything using babel-preset-env. async/await is, though. You can see here in the Babel playground that
const x = () => new Promise((res) => res('hi'));
const y = async () => {
const z = await x();
};
gets transpiled to
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
var x = function x() {
return new Promise(function (res) {
return res('hi');
});
};
var y = function () {
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
var z;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return x();
case 2:
z = _context.sent;
case 3:
case 'end':
return _context.stop();
}
}
}, _callee, undefined);
}));
return function y() {
return _ref.apply(this, arguments);
};
}();
using the default env settings. If you change the env string to, say, chrome>60 (or, in fact, interestingly >4%!), the code is passed through as-is, as Chrome > 60 supports async/await and arrow functions natively.
I am running an easy Sharepoint Framework project in Visual Studio Code:
I have this structure:
My files are as follows:
ComplexCalculator.ts
export class ComplexCalculator {
public sqr(v1: number): number {
return v1*v1;
}
public multiply(v1:number, v2:number): number {
return v1*v2;
}
}
EasyCalculator.ts
export class EasyCalculator {
public sum(v1: number, v2: number): number {
return v1 + v2;
}
public subtraction(v1: number, v2: number): number {
return v1 - v2;
}
}
Calculator.ts
export * from './ComplexCalculator';
export * from './EasyCalculator';
Calculator.manifest.json
{
"$schema": "../../../node_modules/#microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "8de800b0-6a4f-4cb0-bf75-62c32e6ea66b",
"componentType": "Library",
"version": "0.0.1",
"manifestVersion": 2
}
On my config.json I have this:
{
"entries": [
{
"entry": "./lib/webparts/librarysample/LibrarysampleWebPart.js",
"manifest": "./src/webparts/librarysample/LibrarysampleWebPart.manifest.json",
"outputPath": "./dist/librarysample.bundle.js"
},
{
"entry": "./lib/libraries/calculator/Calculator.js",
"manifest": "./src/libraries/calculator/Calculator.manifest.json",
"outputPath": "./dist/calculator.bundle.js"
}
],
"externals": {
"#microsoft/sp-client-base": "node_modules/#microsoft/sp-client-base/dist/sp-client-base.js",
"#microsoft/sp-client-preview": "node_modules/#microsoft/sp-client-preview/dist/sp-client-preview.js",
"#microsoft/sp-lodash-subset": "node_modules/#microsoft/sp-lodash-subset/dist/sp-lodash-subset.js",
"office-ui-fabric-react": "node_modules/office-ui-fabric-react/dist/office-ui-fabric-react.js",
"react": "node_modules/react/dist/react.min.js",
"react-dom": "node_modules/react-dom/dist/react-dom.min.js",
"react-dom/server": "node_modules/react-dom/dist/react-dom-server.min.js",
"calculator": "./dist/calculator.bundle.js"
},
"localizedResources": {
"librarysampleStrings": "webparts/librarysample/loc/{locale}.js"
}
}
and finally on my gulpfile.js
const gulp = require('gulp');
const build = require('#microsoft/sp-build-web');
var through = require('through2'),
util = require('gulp-util'),
spawn = require('child_process').spawn,
clean = require('gulp-clean'),
ts = require('gulp-typescript');
build.initialize(gulp);
var libsPath = 'lib/libraries';
var srcPath = 'src/libraries';
var calculatorLibraryFolder = 'calculator';
gulp.task('watch-calculator-lib', (cb) => {
var watcher = gulp.watch(`${srcPath}/${calculatorLibraryFolder}/**/*.ts`, ['update-calculator-typings']);
watcher.on('change', (event) => {
console.log(`File ${event.path} was ${event.type}, Rebuilding library typings...`);
});
});
gulp.task('update-calculator-typings', [
'update-calculator-typings:clean-old-typings',
'update-calculator-typings:get-latest-typings',
'update-calculator-typings:build-lib-typings'
], () => {
});
gulp.task('update-calculator-typings:clean-old-typings', () => {
return gulp.src(`${libsPath}/${calculatorLibraryFolder}/**`, { read: false })
.pipe(clean());
});
gulp.task('update-calculator-typings:get-latest-typings', ['update-calculator-typings:clean-old-typings'], () => {
var tsResult = gulp.src(`${srcPath}/${calculatorLibraryFolder}/**/*.ts`)
.pipe(ts({
outDir: `${libsPath}/${calculatorLibraryFolder}`,
module: 'umd',
declaration: true
}));
return tsResult.dts.pipe(gulp.dest(`${libsPath}/${calculatorLibraryFolder}`));
});
gulp.task('update-calculator-typings:build-lib-typings', ['update-calculator-typings:get-latest-typings'], () => {
return gulp.src(`${libsPath}/${calculatorLibraryFolder}/**/*.d.ts`)
.pipe(updateLibTypings('calculator.d.ts'))
.pipe(gulp.dest('./typings'));
});
var updateLibTypings = function (typingsFilePath, opt) {
var typings = ["declare module 'calculator' {"];
var latestFile;
function processTypings(file, encoding, cb) {
if (file.isNull() || file.isStream()) {
cb();
return;
}
latestFile = file;
var contents = file.contents.toString('utf8');
if (contents.indexOf('export declare class ') === -1) {
cb();
return;
}
contents = contents.replace('export declare class ', 'class ');
typings.push(contents);
cb();
}
function endStream(cb) {
if (!latestFile) {
cb();
return;
}
typings.push('}');
var file = latestFile.clone({ contents: false });
file.path = latestFile.base + typingsFilePath;
file.contents = new Buffer(typings.join('\r\n'));
this.push(file)
cb();
}
return through.obj(processTypings, endStream);
}
the typings file is generated correctly on the dist folder
calculator.d.ts
declare module 'calculator' {
class ComplexCalculator {
sqr(v1: number): number;
multiply(v1: number, v2: number): number;
}
class EasyCalculator {
sum(v1: number, v2: number): number;
subtraction(v1: number, v2: number): number;
}
}
However, when I try to reference it into my webpart file
import * as calculator from 'calculator';
and then I try to compile
I get this error
Error - typescript - src/webparts/librarysample/LibrarysampleWebPart.ts(13,29): error TS2307: Cannot find module 'calculator'.
Your code import * as calculator from 'calculator'; is wrong. You need to import modules in your project using relative paths. e.g.
import * as calculator from './path/to/Calculator';
More
Be careful about file casing. I prefer camelCase for consistency.
Master node_modules : https://nodejs.org/docs/latest/api/modules.html