Unable to merge mochaweasome reports - javascript

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

Related

config error : Invalid value undefined for HardhatConfig.networks.paths.url

this is my hardhat.config.js file code :
require("#nomiclabs/hardhat-waffle");
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
networks : {
hardhat :{
chainId: 1337,
},
paths :{
artifacts: "./src/artifacts",
},
},
};
and when i compile this using npx hardhat compile
it shows following error :
Error HH8: There's one or more errors in your config file:
Invalid value undefined for HardhatConfig.networks.paths.url - Expected a value of type
string.
To learn more about Hardhat's configuration, please go to https://hardhat.org/config
for your reference i am following this tutorial for building this web3 project : "https://blog.suhailkakar.com/setup-and-build-your-first-web-3-application"
You have to close the network's bracket after the hardhat chain Id :)
Please replace your module.exports object with this
module.exports = {
solidity: "0.8.4",
networks:{
hardhat:{
chainId: 1337,
}
},
paths:{
artifacts: "./src/artifacts"
}
};
P.S: Thanks for pointing this out, I have also updated my article
Required dotenv before using process.env values in hardhat.config.js
require("#nomicfoundation/hardhat-toolbox")
require("dotenv").config()
const RINKEBY_RPC_URL = process.env.RINKEBY_RPC_URL
const PRIVATE_KEY = process.env.PRIVATE_KEY
const PRIVATE_KEY_USER1 = process.env.PRIVATE_KEY_USER1
/** #type import('hardhat/config').HardhatUserConfig */
module.exports = {
defaultNetwork: "hardhat",
solidity: {
compilers: [
{ version: "0.8.8" },
{ version: "0.6.6" },
{ version: "0.8.16" },
],
},
networks: {
rinkeby: {
url: RINKEBY_RPC_URL,
accounts: [PRIVATE_KEY, PRIVATE_KEY_USER1],
chainId: 4,
},
},
}

How to avoid [Vue warn] for custom directive?

I created a custom directive and it's working good, but when I run the mocha test for the component where I use this custom directive I receive this warning message [Vue warn]: Failed to resolve directive: scroll-text, tell me please how to fix that
test file:
import { shallowMount } from "#vue/test-utils"
import { scrollText } from "z-common/services"
import ZSourcesList from "./ZSourcesList"
Vue.use(scrollText)
const stubs = [
"z-text-field",
"v-progress-circular",
"v-icon",
"z-btn"
]
describe("ZSourcesList.vue", () => {
const sources = []
for (let i = 0; i < 20; i++) {
sources.push({
field: "source",
// format numbers to get 2 diggit number with leading zero 1 -> 01
value: `cluster-${i.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false })}`,
__typename: "SuggestV2Result"
})
}
it("displays 'No matching sources found' if there are no sources", () => {
const wrapper = shallowMount(ZSourcesList, {
mocks: {
$apollo: {
queries: {
suggestions: {
loading: false,
},
},
},
},
stubs,
sync: false,
data() {
return {
suggestions: [],
}
},
})
expect(wrapper.find(".notification .z-note")).to.exist
})
})
Try registering your custom directive on a local vue instance and then mounting to that local vue instance.
import { shallowMount, createLocalVue } from "#vue/test-utils"
import { scrollText } from "z-common/services"
import ZSourcesList from "./ZSourcesList"
const localVue = createLocalVue()
localVue.use(scrollText) // Register the plugin to local vue
const stubs = [
"z-text-field",
"v-progress-circular",
"v-icon",
"z-btn"
]
describe("ZSourcesList.vue", () => {
const sources = []
for (let i = 0; i < 20; i++) {
sources.push({
field: "source",
// format numbers to get 2 diggit number with leading zero 1 -> 01
value: `cluster-${i.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false })}`,
__typename: "SuggestV2Result"
})
}
it("displays 'No matching sources found' if there are no sources", () => {
const wrapper = shallowMount(ZSourcesList, {
mocks: {
$apollo: {
queries: {
suggestions: {
loading: false,
},
},
},
},
localVue, // Mount this component to localVue
stubs,
sync: false,
data() {
return {
suggestions: [],
}
},
})
expect(wrapper.find(".notification .z-note")).to.exist
})
})
Using a local vue instance instead of the global in test cases will also prevent polluting the global vue instance and help to prevent side effects in other test cases.

Run additional asertion code after Botium Bindings completes

How can I run additional assertion after Botium Binding is completed?
const bb = new BotiumBindings({ convodirs: ['/spec'] })
BotiumBindings.helper.mocha().setupMochaTestSuite({ bb })
// TODO: GET request to an external API.
The recommended way to add your custom asserter logic to Botium is by adding your own asserter module to Botium. You can find the details here, but in short:
Create a file MyCustomAsserter.js:
module.exports = class CustomAsserter {
constructor (context, caps, globalArgs) {
this.context = context
this.caps = caps
this.globalArgs = globalArgs
}
assertConvoStep ({convo, convoStep, args, isGlobal, botMsg}) {
if (botMsg.message !== 'hugo') throw new Error('expected hugo')
return Promise.resolve()
}
}
Register it in botium.json
{
"botium": {
"Capabilities": {
...
"ASSERTERS": [
{
"ref": "MY-ASSERTER-NAME",
"src": "./MyCustomAsserter.js",
"global": false,
"args": {
"my-arg-1": "something"
}
}
]
}
}
}
Use this asserter in your convo files:
my-test-case
#me
hi
#bot
hi
MY-ASSERTER-NAME some-arg1|some-arg2

Jest encountered an unexpected token: implementing try/catch

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)
})
}

How to write maintainable JavaScript ala' Bash scripts with advanced reporting features?

I would like to write a script to execute backup procedure for multiple computers in an office. How can I write in a way that I can granually control execution path and also is easy to read and modify? Do I need OOP and SOLID?
The script should make sure that a computer is alive, if not WoL it and leave it in initial state after backup.
Also, the script should do a couple of basic health checks such as smartctl -H and after that execute rsync ... and brtbk ... commands to do the actual backup.
I would like the script to produce a one page report sent to an email address with a clear title indicating wether I should investigate or I can ignore the email.
I already tried to write this in vanilla JS with async/await but failed because of a complex configuration JSON I came up with.
var task = {
type: 'main',
config: {
host: '10.5.1.158',
mac: 'e0:d5:5e:ee:de:3d',
},
task: {
type: 'ensureAlive',
task: [
{
type: 'smartCheck',
dev: '/dev/sda'
},
{
type: 'smartCheck',
dev: '/dev/sdb'
},
{
type: 'failEarly',
task: [
{
type: 'rsync',
config: {
from: `root#{{config.ip}}:/home/VirtualBox\ VMs/a15:/backups/a15/vms/a15/`,
to: '/backups/a15/',
}
},
{
type: 'btrfsSnapshot',
config: {
dir: '/backups/a15/',
},
}
]
}
]
}
};
async function run(ctx, task) {
if (!task) {
return;
}
if (Array.isArray(task)) {
for (var i = 0; i < task.length; i++) {
await run(ctx, task[i]);
}
return;
}
var config = Object.assign({}, ctx.config || {}, task.config || {});
var f = ctx.getFunction(task.type);
try {
var result = await f(config);
task.output = result;
} catch (error) {
task.output = Output({ isOk: false, errorMessage: error.message, errorStack: error.stack })
}
var newCtx = Object.assign({}, ctx, { config });
await run(newCtx, task.task);
}
The recurring run function became too complex to understand and modify/add features.
I was expecting to get something as easy to read as this, no matter wether this is JSON or actual JavaScript. Pseudocode below:
async function a15(report) {
var wasAlive = wakeUp();
try {
await smartCheck();
} catch (error) {
report.addError(error);
}
try {
await smartCheck();
} catch (error) {
report.addError(error);
}
try {
await rsync();
await btrbk();
} catch (error) {
report.addError(error);
}
if (!wasAlive) {
shutDown();
}
}
What am I doing wrong? Is this even possible?
For extra clarification I would like to attach additional config layouts I tried.
Another config try which happened to be too complex to program. Since this config is flat, the main difficulty is related to passing a variable indicating that host is alive (at wakeUp) to the end of the config (at shutDown).
var a15: TaskDescription[] = [
{
type: 'wakeUp',
config: {
host: '10.5.1.252',
mac: 'e0:d5:5e:ee:de:3d'.replace(/:/g, ''),
timeout: '5',
user: 'root',
privateKey: '/Users/epi/.ssh/id_rsa',
},
},
{
type: 'smartCheck',
config: {
dev: '/dev/sda',
},
},
{
type: 'smartCheck',
config: {
dev: '/dev/sdb',
},
},
{
type: 'command',
configTemplateFromConfig: true,
config: {
command: 'rsync -a --inplace --delete -e ssh root#{{host}}:/home/santelab/VirtualBox\ VMs/a15:/mnt/samsung_m3/a15/ /backups/a15/'
},
},
{
type: 'command',
config: {
command: 'btrbk -c /mnt/samsung_m3/a15.conf run'
},
},
{
type: 'shutDown',
runIf: 'wasAlive',
config: {
host: '10.5.1.252',
mac: 'e0:d5:5e:ee:de:3d'.replace(/:/g, ''),
timeout: '5',
user: 'root',
privateKey: '/Users/epi/.ssh/id_rsa',
},
},
];
export interface TaskDescription {
type: string;
config?: TaskConfig;
configTemplateFromConfig?: boolean;
ignoreError?: boolean;
runIf?: string;
}
export type TaskConfig = {
[key: string]: string,
}
I think I made it.
There are 2 key concepts that are required:
never throw an error, always return a result that wraps error and value
use generators - yield magic
Here is a proof of concept for localhost writen in TypeScript. I could use JavaScript as well.
import { WakeUp, Config as WakeUpConfig, Result as WakeUpResult } from './WakeUp';
import { SmartCheck, Config as SmartCheckConfig } from './SmartCheck';
import { Command, Config as CommandConfig, Result as CommandResult } from './Command';
import * as I from './interfaces';
async function* localhost() {
var wakeUpResult = (yield WakeUp({ host: 'localhost', mac: 'e0:d5:5e:ee:de:3d', timeout: 5, tries: 20 })) as WakeUpResult;
if (wakeUpResult.error) { return; }
var echoResult = (yield Command({ command: `echo test` })) as CommandResult;
if (echoResult.error) { return; }
if (!wakeUpResult.value) {
yield Command({ command: 'echo shutdown' });
}
}
(async function () {
var iterator = localhost();
var lastResult: IteratorResult<any> = { value: undefined, done: false };
do {
lastResult = await iterator.next(lastResult.value);
} while (!lastResult.done);
})()
I think the core localhost() is easy to read and allows for easy modifications.

Categories