How to trigger cypress after:run after tests finish execution - javascript

I'm using cypress + multiple-cucumber-html-report to generate a report after execution. There is the possibility to add custom data to the report such as execution start and end time.
I assume this information somehow comes from cypress as part of the result meta data.
I tried to put results in json file after the run finishes, by adding it to the cypress config file:
import { defineConfig } from 'cypress';
import * as fs from 'fs';
async function setupNodeEvents(on, config) {
on('after:run', async (results) => {
if (results) {
fs.mkdirSync("cypress/.run", { recursive: true });
fs.writeFile("cypress/.run/results.json", JSON.stringify(results), (err) => {
if (err)
console.log(err);
else {
console.log("Successful results has been written");
}
});
}
})
return config;
}
export default defineConfig({
e2e: {
setupNodeEvents,
experimentalInteractiveRunEvents: true
},
});
then read these results in the report generation file:
const report = require('multiple-cucumber-html-reporter');
const fs = require('fs');
fs.readFile('cypress/.run/results.json', function read(err, data) {
if (err) {
throw err;
}
var runInfos = JSON.parse(data);
report.generate({
jsonDir: './cypress/result/',
reportPath: './cypress/report/',
metadata:{
browser: {
name: runInfos.browserName,
version: runInfos.browserVersion
},
device: 'Cypress',
platform: {
name: mapOs(runInfos.osName)
}
},
customData: {
title: 'Run info',
data: [
{label: 'Project', value: 'project'},
{label: 'Execution Start Time', value: new Date(runInfos.startedTestsAt).toLocaleString()},
{label: 'Execution End Time', value: new Date(runInfos.endedTestsAt).toLocaleString()}
]
}
});
});
unfortunately the after:run was never triggered, and not even throwing an error.

Take a look at the docs on After Run API
When running via cypress open, the after:run event only fires if the experimentalInteractiveRunEvents flag is enabled.
Unfortunately, from the look of your config sample you must be using an older version of Cypress (pre v10).
To make this more useful, upgrade Cypress the use the flag mentioned above like this:
// cypress.config.js
const { defineConfig } = require('cypress')
module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('after:run', (results) => {
/* ... */
})
},
experimentalInteractiveRunEvents: true, // here is the flag, not documented in the configuration page
},
})

Related

Not able register hapi-cron-job plugin

I am trying to schedule cronjobs which will run at specified time, i am using hapi-cron-job of hapi, when i try to register the plugin, i am getting below error.
[1] "plugin.register" must be of type function
at Object.exports.apply (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\config.js:19:15)
at internals.Server.register (D:\my_dir\Repositories\repo-cronjobs\node_modules\#hapi\hapi\lib\server.js:454:31)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Please find the configuration while registering the plugin.
server.js
const { plugins } = require('./register/index');
await server
.register(plugins)
.then(() => {})
.catch(err => {
console.error('Plugin registeration failed!');
console.error(err);
});
index.js
module.exports.plugins = [
// I have here other pluguns, passing this array for registration in server.js
require("./hapi-cron-job-plugin")
];
hapi-cron-job-plugin.js
const hapiCronJob = require('hapi-cron-job')
const plugin = {
register: require('hapi-cron-job'),
options: {
jobs: [
{
name: "diplay time",
enabled: true,
immediate: true,
schedule: "every 1 s",
execute: alertSystemAdminAndDispatcher,
environments: ['development', 'staging']
}
],
}
}
module.exports = plugin;
nodeJS version: v14.17.3
Hapi-cron-job: "hapi-cron-job": "^2.0.1"

Using console log in Knex migration not logging

My issue: The console.log('tableNobject: ', tableNobject) does not log in knex migration.
The following code is what I have tried:
// solution A
export async function up(knex: Knex) {
const tableAobject = await knex.select('*').from('tableAobject');
console.log('tableAobject: ', tableAobject);
}
// solution B
export async function up(knex: Knex) {
await knex.select('*').from('tableBobject').then((tableBobject) => {
console.log('tableBobject: ', tableBobject);
});
}
However my terminal output is the following:
Migration Starting ...
Migrated
Migration Done.
These logs come from our migration script where we call database.migrate.latest()
My expected terminal output for the code above would be something like this:
Migration Starting ...
tableNobject: [
{
id: 'randomId'
someData: 'someDataString'
...
},
...
]
Migrated
Migration Done.
I know logging tables that you get from knex is possible because when I set up a test script outside the migration flow I can log the table without issues.
I have tried the following addition of settings:
const configA = {
...
debug: true,
}
const configB = {
...
log: {
warn(message) {
console.log(message)
},
error(message) {
console.log(message)
},
deprecate(message) {
console.log(message)
},
debug(message) {
console.log(message)
},
}
}
const configC = {
...
debug: true,
log: {
warn(message) {
console.log(message)
},
error(message) {
console.log(message)
},
deprecate(message) {
console.log(message)
},
debug(message) {
console.log(message)
},
}
};
The different settings above dont give me the logging in the terminal as I want.
The base settings (I dont know if this gives an added value):
const config = {
client: 'postgresql',
connection: {
host: '127.0.0.1',
port: '5432',
database: 'projectName_develop',
user: 'user',
password: 'dev',
},
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: 'knex_migrations',
directory: path.join(__dirname, 'migrations'),
},
seeds: {
directory: path.join(__dirname, 'seeds'),
},
asyncStackTraces: true,
};
So the reason why my console.log didnt log was because the migrations are TypeScript files.
I forgot to run the command: npm run build-ts-backed:watch
So the solution was easier than the issue at hand. Please remember to run your TypeScript compiler when you test in TypeScript.

Issue with Cypress.js and uncaught exceptions

I'm very new to Cypress.js.
Problem statement:
I'm running cypress in headless mode (Chrome) and one of the API calls is failing with uncaught exception. However, when I manually visit the url it works fine!
I'm not sure if its because of some SSL certificate issue or what's happening. Everything works normally when I visit the url in my chrome/firefox/safari.
Follow-up questions:
My recording shows it's uncaught exception but I don't know why / what is failing.
How do I log my failing network requests into a log file to see what the actual error is?
Am I missing any configuration?
This is my configuration:
cypress/plugins/index.js
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on('before:browser:launch', (browser = {}, launchOptions) => {
launchOptions.args.push('--ignore-urlfetcher-cert-requests')
launchOptions.args.push(`--ignore-certificate-errors`)
launchOptions.args.push(`--unsafely-treat-insecure-origin-as-secure=http://localhost:9999`)
return launchOptions
})
}
Cypress.json
{
"reporter": "junit",
"reporterOptions": {
"mochaFile": "cypress/results/helltool.xml",
"toConsole": true
},
"defaultCommandTimeout": 20000,
"pageLoadTimeout": 20000,
"responseTimeout": 20000,
"chromeWebSecurity": false
}
Sample Test
Cypress.on('uncaught:exception', (err, runnable) => {
console.log(`CYPRESS uncaught exception FLOW:::: ${err}`);
debugger;
return false;
});
describe('Flow Sanity Tests', () => {
before(() => {
// We need to login before we can do anything
// TODO: Abstract this inside Looker.explore
cy.login('admin', { flow: true })
})
it('Test to check Flow exists and run it', () => {
// Some test to execute after login
})
Login flow (in support/commands.js)
Cypress.Commands.add('login', (userType, options = {}) => {
const types = {
admin: {
email: 'demo#demo',
password: 'thisisademopassword',
},
}
// Go to login page
cy.goTo('login', options)
// grab the user
const { email, password } = types[userType]
cy.wait(2000)
// type the stuff.
cy.get('#login-email', { timeout: 30000 }).should('exist').debug()
cy.get('#login-email').type(email)
cy.get('#login-password').type(password)
cy.get('#login-submit').click()
})
Execution:
npm run cypress:run -- --spec "cypress/integration/flow/demo.spec.js"
--browser chrome

msw mockServiceWorker.js resource remains in a"pending" status when I open the network tab of my browser

I am using msw to mock fetch API request in my project, I check the network tab and the mockServiceWorker.js resource remains in a"pending" status, additionally, the response retrieves index.html instead of the JSON response I mock in the handlers file. Maybe I am incurring a silly error but I didn't find some resource on the web that could help me, thanks in advance!
Environment
Name
Version
msw
0.28.2
browser
Chrome 90.0.4430.93
OS
Windows 10
Request handlers
I run "dev": "webpack serve --mode development", in CLI and these are my configurations
// index.tsx
...
if (process.env.NODE_ENV === 'development') require('./mocks/browser');
const rootElement = document.getElementById('app');
ReactDOM.render(<ThemeProvider><App /></ThemeProvider>, rootElement);
// ./mock/browser.ts
import { setupWorker } from 'msw';
import { handlers } from './handlers';
const worker = setupWorker(...handlers);
worker.start();
// handlers
import { rest } from 'msw';
const baseURL = 'http://localhost:8080';
const handlers = [
rest.get(`${baseURL}/navlink-routes`, (_req, res, ctx) => res(
ctx.status(200),
ctx.json({
result: [
{ label: 'Shop', path: 'shop' },
{ label: 'Wishlist', path: 'wishlist' },
{ label: 'Checkout', path: 'checkout' },
],
}),
)),
rest.get('*', (req, res, ctx) => res(
ctx.status(500),
ctx.json({ error: `Please add request handler for ${req.url.toString()}` }),
)),
];
export { handlers };
Actual request
// Example of making a request. Provide your code here.
async function getData(): Promise<void> {
try {
const response = await fetch('http://localhost:8080/navlink-routes', { signal });
if (!response.ok) throw new Error(`Server error ${response.status}`);
const { result } = await response.json();
setLinkList(result);
} catch (e) {
if (e.name !== 'AbortError') setError(true);
}
}
Thanks to #kettanaito I realize that I wasn't set up a public directory properly I was using my dist directory which I created for production purposes calling:
webpack --mode production
Following the suggestion, I created a new public/ directory and call:
npx msw init public
That solves the issue 👍

How download file via ipfs using Nodejs?

I am trying to implement IPFS in an application made with NodeJS. I can add file and get the CID, but if I try to download it with ipfs get <CID> it does not download anything. Any ideas what can be ?. I use this code to start an IPFS node:
const IPFS = require('ipfs');
// Spawn your IPFS node \o/
const node = new IPFS();
node.on('ready', () => {
node.id((err, id) => {
if (err) {
return console.log(err)
}
console.log(id)
})
let files = [
{
path: '/home/my/file.jpg',
content: File.read('/home/my/file.jpg', null)
}
]
node.files.add(files, function (err, files) {
if (err) {
console.log(err);
} else {
console.log(files)
}
})
})
When you start the node application, you will get some output like this:
[ { path: 'home/my/Pictures',
hash: '...hash',
size: 10329 },
{ path: 'home/my',
hash: '...hash',
size: 10384 },
{ path: 'home',
hash: '...hash',
size: 10435 },
{ path: '/home/my/Pictures/google.png',
hash: 'QmYeznhKxbZY37g5ymFzWnmrbP8ph2fdxycAuw9S9goUYr',
size: 10272 } ]
then copy that file hash, make sure you can access that file from the browser.
// replace the hash code for your own need
https://ipfs.io/ipfs/QmYeznhKxbZY37g5ymFzWnmrbP8ph2fdxycAuw9S9goUYr
then download the file in your terminal
// replace the hash code for your own need
ipfs get QmYeznhKxbZY37g5ymFzWnmrbP8ph2fdxycAuw9S9goUYr -o=google.png
Check here for more options
From nodejs you can do something like this provided necessary packages are imported:
const fileHash = 'you hash of the file you want to get'
ipfs.files.get(fileHash, function (err, files) {
files.forEach((file) => {
console.log(file.path)
console.log("File content >> ",file.content.toString('utf8'))
})
})

Categories