Unhandled error while running jest-puppeteer test - jestjs

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;

Related

Shopify node api context initalize errors out

I'm trying to make an app following these directions:
https://github.com/Shopify/shopify-node-api/blob/main/docs/getting_started.md
I have all the code configred and it looks like this:
// src/index.ts
import http from 'http';
import url from 'url';
import querystring from 'querystring';
import Shopify, { ApiVersion } from '#shopify/shopify-api';
require('dotenv').config();
const { API_KEY, API_SECRET_KEY, SCOPES, SHOP, HOST } = process.env
Shopify.Context.initialize({
API_KEY,
API_SECRET_KEY,
SCOPES: [SCOPES],
HOST_NAME: HOST.replace(/https?:\/\//, ""),
HOST_SCHEME: HOST.split("://")[0],
IS_EMBEDDED_APP: {boolean},
API_VERSION: ApiVersion.{version} // all supported versions are available, as well as "unstable" and "unversioned"
});
// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS: { [key: string]: string | undefined } = {};
async function onRequest(
request: http.IncomingMessage,
response: http.ServerResponse,
): Promise<void> {
const {headers, url: req_url} = request;
const pathName: string | null = url.parse(req_url).pathname;
const queryString: string = String(url.parse(req_url).query);
const query: Record<string, any> = querystring.parse(queryString);
switch (pathName) {
default:
// This shop hasn't been seen yet, go through OAuth to create a session
if (ACTIVE_SHOPIFY_SHOPS[SHOP] === undefined) {
// not logged in, redirect to login
response.writeHead(302, {Location: `/login`});
response.end();
} else {
response.write('Hello world!');
// Load your app skeleton page with App Bridge, and do something amazing!
}
return;
} // end of default path
} // end of onRequest()
http.createServer(onRequest).listen(3000);
Package JSON looks like this:
{
"name": "shopify-checkout-apit",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"#shopify/shopify-api": "^3.1.0"
},
"devDependencies": {
"#types/node": "^17.0.40",
"dotenv": "^16.0.1",
"typescript": "^4.7.3"
},
"scripts": {
"build": "npx tsc",
"prestart": "yarn run build",
"start": "node dist/index.js"
}
}
When I go to run the app with yarn start I get a ton of errors
PS C:\Users\kawnah\shopify-checkout-apit> yarn start yarn run v1.22.18
$ yarn run build $ npx tsc src/index.ts:17:27 - error TS1003:
Identifier expected.
17 API_VERSION: ApiVersion.{version} // all supported versions are
available, as well as "unstable" and "unversioned"
~
src/index.ts:18:1 - error TS1005: ',' expected.
18 }); ~
Found 2 errors in the same file, starting at: src/index.ts:17
error Command failed with exit code 2. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command. error Command failed with exit code 2. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command. PS C:\Users\kawnah\shopify-checkout-apit>
I have no idea what any of this means.
Typescript Error TS1003 when attempting to access object properties using bracket notation
Why does this trigger an Identifier Expected error in Typescript?
I tried deleting node modules and reinstalling but it didn't work.
How do you fix this?
the config needs to look like this
Shopify.Context.initialize({
API_KEY,
API_SECRET_KEY,
SCOPES: [SCOPES],
HOST_NAME: HOST.replace(/https?:\/\//, ""),
HOST_SCHEME: HOST.split("://")[0],
IS_EMBEDDED_APP: true,
API_VERSION: ApiVersion.October21 // all supported versions are available, as well as "unstable" and "unversioned"
});

newman, postman's cli runner, can not find a custom reporter

When I run newman with a custom reporter it can not find it, and the error states the reporter should be installed in the newman directory. I am on windows 10. It is named newman-reporter-csvconsole. Where is the newman default directory, to look for reporters?
the reporter package index.js
function csvconsole (emitter, reporterOptions, collectionRunOptions) {
emitter.on('start',function (err, args)
{ // on start of run, log to console
console.log('running a collection...');
});
}
module.exports = csvconsole;
I then install a local package
C:\Users<user>\AppData\Roaming\npm\node_modules\newman\newman-reporter-csvconsole>npm init -w newman-reporter-csvconsole -S
C:\Users<user>\AppData\Roaming\npm\node_modules\newman\newman-reporter-csvconsole>npm pack
C:\Users<user>\AppData\Roaming\npm\node_modules\newman>npm install -S ./csvconsoleReporter/newman-reporter-csvconsole-1.0.0.tgz
The package and pack-lock files
C:\Users<user>\AppData\Roaming\npm\node_modules\newman\package.json
"dependencies": {
...
"newman-reporter-csvconsole": "file:newman-reporter-csvconsole",
...
C:\Users<user>\AppData\Roaming\npm\node_modules\newman\package-lock.json
"dependencies": {
...
"newman-reporter-csvconsole": "file:newman-reporter-csvconsole",
...
"newman-reporter-csvconsole": {
"version": "1.0.0",
"license": "ISC"
},
...
"node_modules/newman-reporter-csvconsole": {
"resolved": "newman-reporter-csvconsole",
"link": true
},
...
"newman-reporter-csvconsole": {
"version": "file:newman-reporter-csvconsole"
},
module.exports = function csvconsole (emitter, reporterOptions, collectionRunOptions)
{
// emitter is is an event emitter that triggers the following events: https://github.com/postmanlabs/newman#newmanrunevents
// reporterOptions is an object of the reporter specific options. See usage examples below for more details.
// collectionRunOptions is an object of all the collection run options:
// https://github.com/postmanlabs/newman#newmanrunoptions-object--callback-function--run-eventemitter
emitter.on('start',function (err, args)
{ // on start of run, log to console
console.log('running a collection...');
});
}

What is the most simplest way of implementing a DELETE request using axios?

I have been unsuccessful in trying to figure out how to solve the following errors, (1st error:)'OPTIONS http://localhost:3000/lists/5a9dca48cebb5a4e5fc1bfe9 404 (Not Found)' and (2nd error:)'Failed to load http://localhost:3000/lists/5a9dca48cebb5a4e5fc1bfe9: Response for preflight has invalid HTTP status code 404.'.
Initially I defined my code along the same lines as the following: https://github.com/20chix/Hotel_System_Vue.js_Frontend/blob/master/src/components/Hello.vue
Seen quite a number of posts similar to my problem, but neither of their suggested solutions have worked for me.
I'm using Vue.js, Axios and Node.js in the back, my collection is defined as follows in MongoDb:
List: {_id:'', name:'', items:
[ {
title: '',
category: ''
}
]
}
GetList.vue:
methods: {
fetchLists(){
let uri = 'http://localhost:3000/lists';
axios.get(uri).then((response) => {
this.List = response.data;
console.log(this.List[3].items[0]);
console.log(this.List);
});
},
DELETE(a_list, id){
$("#myModal").modal('show');
this.list = a_list;
this._id = id;
},
deleteList : function(_id){
// let uri = 'http://localhost:3000/lists/'+_id;
// this.List.splice(_id, 1);
axios.delete('http://localhost:3000/lists/'+_id)
.then((response) => {
this.fetchLists();
//refreshes Application
// window.location.reload();
})
.catch((error) => {
console.log(error);
});
}
ListController:
exports.delete_a_list = function(req, res)=>{
console.log(req.params);
List.deleteOne({req.params.listId}, function(err, list){
if(err){res.json(err);};
else
{res.json({list: 'List successfully deleted'});}
};
});
UPDATE:
Upon running 'npm install cors --save', it was stored in my package.json .
server/package.json:
{
"name": "api",
"version": "1.0.0",
"description": ":)",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [
":)"
],
"license": "ISC",
"devDependencies": {
"nodemon": "^1.17.1"
},
"dependencies": {
"cors": "^2.8.4",
"express": "^4.16.2",
"mongoose": "^5.0.8",
"npm": "^5.7.1"
}
}
UPDATE:
I tried the following too:
ObjectID = require('mongodb').ObjectID;
exports.delete_a_list = function(req, res){
// console.log(req.params);
List.deleteOne({
_id: ObjectID(req.params.listId)}, function(err, list){
if(err)
res.json(err);
res.json({list: 'List successfully deleted'});
});
};'
This returns the same error including:
xhr.js?ec6c:178 OPTIONS http://localhost:3000/lists/undefined 404 (Not Found)
dispatchXhrRequest # xhr.js?ec6c:178
xhrAdapter # xhr.js?ec6c:12
dispatchRequest # dispatchRequest.js?c4bb:59
Promise.then (async)
request # Axios.js?5e65:51
Axios.(anonymous function) # Axios.js?5e65:61
wrap # bind.js?24ff:9
deleteList # GetList.vue?c877:131
boundFn # vue.esm.js?efeb:190
click # GetList.vue?d584:124
invoker # vue.esm.js?efeb:2004
fn._withTask.fn._withTask # vue.esm.js?efeb:1802
:1 Failed to load http://localhost:3000/lists/undefined: Response for preflight has invalid HTTP status code 404.
createError.js?16d0:16 Uncaught (in promise) Error: Network Error
at createError (createError.js?16d0:16)
at XMLHttpRequest.handleError (xhr.js?ec6c:87)
Thank you guys for all your suggestions.
I found the following video: https://www.youtube.com/watch?v=NEFfbK323Ok, from The Net Ninja, and was able to get it to finally work upon changing my code to reflect his particular method:
listRoutes.js:
app.route('/lists/:_id')
.get(lists.read_a_list)
// .update(lists.update_a_list)
.delete(lists.delete_a_list);
listController.js:
exports.delete_a_list = function(req, res){
// console.log(req.params);
List.findByIdAndRemove({_id: req.params._id}).then(function(list){
res.send(list);
});
};
GetList.vue:
deleteList : function(_id, List){
axios.delete('http://localhost:3000/lists/'+_id, List)
.then(response => {
this.List.splice(index, 1);
//refreshes Application
// window.location.reload();
})
}
Your problem ist related to CORS (cross-origin-resource-sharing).
If you are using node with express then just include this middleware:
https://www.npmjs.com/package/cors
This query seems wrong:
List.deleteOne({req.params.listId}, ...
Can you try modifying it like this?:
List.deleteOne({_id: ObjectID(req.params.listId}), ...
(You need to have ObjectID declared somewhere up: ObjectID = require('mongodb').ObjectID)

TypeError: Cannot read property 'address' of undefined supertest

I need some help to resolve my problem with testing on nodejs codes. I'm using mocha and supertest. I'm confused with the implementation in supertest. I don't know to resolved it. I'm trying to automate downloading a file.
describe('GET /entry/:entryId/file/:id/download', function(){
it('should pass download function', function(done){
this.timeout(15000);
request(app.webServer)
.get('/entry/543CGsdadtrE/file/wDRDasdDASAS/download')
.set('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGco')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
console.log(err, res);
done();
});
});
});
I received a similar error from mocha when testing an express app. Full text of error:
0 passing (185ms)
2 failing
1) loading express responds to /:
TypeError: app.address is not a function
at Test.serverAddress (test.js:55:18)
at new Test (test.js:36:12)
at Object.obj.(anonymous function) [as get] (index.js:25:14)
at Context.testSlash (test.js:12:14)
2) loading express 404 everything else:
TypeError: app.address is not a function
at Test.serverAddress (test.js:55:18)
at new Test (test.js:36:12)
at Object.obj.(anonymous function) [as get] (index.js:25:14)
at Context.testPath (test.js:17:14)
I fixed it by adding this to my express server.js, i.e. export the server object
module.exports = app
Typescript users, who are facing this error, check two things:
The express server should have module.exports = app (thanks to #Collin D)
Use import * as app from "./app"
instead of wrong import app from "./app"
I was facing same problem, above solution didn't work for me, some one in my shoes
kindly follow this guy's
exports in server.js should be
module.exports.app = app;
If you have multiple modules than use es6 feature
module.exports = {
app,
something-else,
and-so-on
}
my package.json for version cross ref..
{
"name": "expressjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha **/*.test.js",
"start": "node app.js",
"test-watch": "nodemon --exec npm test"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"hbs": "^4.0.1"
},
"devDependencies": {
"mocha": "^5.2.0",
"supertest": "^3.3.0"
}
}

cloud9 crypto is not working at all been trying for days

I am trying to get a setup work with utils, the problem is it can not find the crypto module.
I have install utils and crypto using npm install then when I run my script
node server.js casper.js
I get this error
Error: Cannot find module 'crypto'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:7
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:117
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:118
TypeError: 'undefined' is not a function (evaluating 'utils.inherits(Nightmare, Casper)')
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareClient.js:21
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareTest.js:16
why can it not find crypto. I have tried all different ways to get this working, but no luck
does any one have any ideas?
package.json file
{
"name": "chat-example",
"version": "0.0.0",
"description": "A chat example to showcase how to use `socket.io` with a static `express` server",
"main": "server.js",
"repository": "",
"author": "Mostafa Eweda <mostafa#c9.io>",
"dependencies": {
"async": "~0.2.8",
"express": "~3.2.4",
"socket.io": "~0.9.14",
"phantomjs": "*",
"casperjs": "*",
"nightmarejs": "*",
"utils": "*",
"casper": "*"
}
}
server.js
var nightmareJS = require('./node_modules/nightmarejs/lib/nightmare').nightmare('test');
nightmareJS.notifyCasperMessage = function(msg) {
if(msg.type == 'statement') {
console.log(msg.msg);
console.log("Nightmare Server says hello.");
}
else if(msg.type == 'dateQuestion') {
console.log(msg.msg);
var d = new Date();
nightmareJS.sendCasperMessage({ time: d.toString(), timeNow: d.getTime()});
}
}
casper.js
casper.start('http://www.google.com', function() {
this.test.assertTitle('Google', 'Google has the correct title');
this.sendMessageToParent({ type: 'statement', msg: 'Hello Nightmare.'})
})
casper.then(function() {
this.waitForMessageResponse({ type: 'dateQuestion', msg: 'What time is it?'}, 'time', function() {
var d = new Date();
this.echo('Nightmare thinks the time is: ' + this.lastDataReceived.time);
this.log('Nightmare thinks the time is: ' + this.lastDataReceived.time, 'debug');
this.test.assert(Math.abs(this.lastDataReceived.timeNow - d.getTime()) < 1000, "Nightmare and Casper's times are within 1000 seconds of each other");
})
});
casper.run(function() {
this.test.done();
});
and then i run the files using
node server.js casper.js
i am trying to get nightmarejs to work but utils cannot find crypto
please someone help i so need this to work

Resources