Electron with strapi, Cannot find module package.json - node.js

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

Related

mocha Unknown file extension ".ts"

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,.

Deploy Node, Express, and MongoDB server to heroku

I created a server using Node, Express, and MongoDB Atlas. Here is the code of this:
server.js:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
// model
let Cards = require('./models/cards.model');
// App config
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
// DB config
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection has been established successfully.");
})
// API Endpoints
// POST parameter
app.post('/tinder/cards', (req, res) => {
const card = req.body;
Cards.create(card, (err, data) => {
if(err){
return res.status(500).send(err)
} else {
return res.status(200).send(data)
}
})
})
// GET parameter
app.get('/', (req, res) => {
return res.status(200).send("Welcome to Tinder Clone Backend with NodeJS, ExpressJS, and MongoDB!!!")
})
app.get('/tinder/cards', (req, res) => {
Cards.find((err, data) => {
if(err) {
return res.status(500).send(err);
} else {
return res.status(200).send(data)
}
})
});
// Listener
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
});
package.json
{
"name": "tinder-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.12.2"
}
}
cards.model.js
// creating database schema using mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const cardsSchema = new Schema({
name: String,
imgUrl: String
});
const Cards = mongoose.model('Cards', cardsSchema);
module.exports = Cards;
It is working locally and all endpoints sending and receiving data from mongodb atlas.
when I run this command in terminal to start the local server:
$ nodemon server
it is showing this:
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server is running on port 5000
MongoDB database connection has been established successfully.
This means that my local server is running well and when I check in my browser and type in my server link i.e http://localhost:5000/tinder/cards, it showing data that I have posted previously:
[
{
"_id": "605a53881dedb514dcc1c4f2",
"name": "Elon Musk",
"imgUrl": "https://s3.india.com/wp-content/uploads/2020/03/Elon-Musk-AP.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f3",
"name": "Shakira",
"imgUrl": "https://ichef.bbci.co.uk/news/976/cpsprodpb/738B/production/_116497592_gettyimages-971720370.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f4",
"name": "Jeff Bezos",
"imgUrl": "https://media.wired.com/photos/6019cab23453f789506008d0/master/pass/Sec_Bezos_1036084400.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f5",
"name": "Dua Lipa",
"imgUrl": "https://assets.vogue.com/photos/5f48136693122510d16f0352/4:3/w_1080,h_810,c_limit/118520052_586967341971321_6121798062289952442_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f6",
"name": "Pitbull",
"imgUrl": "https://vz.cnwimg.com/wp-content/uploads/2010/03/Pitbull.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f7",
"name": "Ellen",
"imgUrl": "https://www.geo.tv/assets/uploads/updates/2021-03-18/340307_5260100_updates.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f8",
"name": "Bill Gates",
"imgUrl": "https://www.incimages.com/uploaded_files/image/1920x1080/getty_1185999101_20001333200092800_443629.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f9",
"name": "Taylor Swift",
"imgUrl": "https://static.onecms.io/wp-content/uploads/sites/20/2020/12/02/taylor-swift1.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fa",
"name": "Engin Altan",
"imgUrl": "https://www.incpak.com/wp-content/uploads/2020/09/50094085_2224186024567959_693900883193935752_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fb",
"name": "Esra Bilgic",
"imgUrl": "https://i.dawn.com/large/2021/01/6007fbceb61de.png",
"__v": 0
}
]
But when I deployed the same server to heroku, it is showing an empty object when I testing it.
When I run this command into my terminal:
$ heroku logs --tails
It is showing this error:
2021-03-25T11:08:08.715303+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: Could not connect to
any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted.
Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2021-03-25T11:08:08.715323+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:839:32)
2021-03-25T11:08:08.715324+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:348:10
2021-03-25T11:08:08.715326+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
2021-03-25T11:08:08.715326+00:00 app[web.1]: at new Promise (<anonymous>)
2021-03-25T11:08:08.715327+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1152:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:347:20)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:23:10)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1063:30)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:928:32)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:769:14)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at internal/main/run_main_module.js:17:47
2021-03-25T11:08:08.715332+00:00 app[web.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2021-03-25T11:08:08.721117+00:00 app[web.1]: (node:21) 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(). To term
inate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html
#cli_unhandled_rejections_mode). (rejection id: 1)
2021-03-25T11:08:08.721508+00:00 app[web.1]: (node:21) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the fut
ure, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
my server that is deployed on heroku is showing empty object instead of that data that I have posted,
when I type URL of heroku server i.e https://tinder-clone-backend-mern.herokuapp.com/tinder/cards :
{}
How can I make this server work perfectly as the local server does?
Try setting IPS, in your Atlas cluster/Network Access, to be available for all IPS (0.0.0.0/0) Let me know if it fixes.

TypeError in Discord.JS-Commando Discord Bot

Ok, so I have a bot built in discord.js-commando. I';ve been doing some tweaking to it, mainly trying to add some more functionality, such as logging commands and such to a channel by name as well as adding console.error logging.
Now my attempts to get channel logging are visible in the commands, however the bot keeps throwing a TypeError.... I have no idea what is causing this error or for that matter how to fix it.
Can someone please take a look at my code and help me figure out what is causing the TypeError?
This is the error I keep getting:
console.error
2020-09-30T23:08:24.272196+00:00 app[worker.1]: TypeError: this.commands.filterArray is not a function
2020-09-30T23:08:24.272208+00:00 app[worker.1]: at CommandRegistry.findCommands (/app/node_modules/discord.js-commando/src/registry.js:438:41)
2020-09-30T23:08:24.272208+00:00 app[worker.1]: at CommandDispatcher.matchDefault (/app/node_modules/discord.js-commando/src/dispatcher.js:254:34)
2020-09-30T23:08:24.272209+00:00 app[worker.1]: at CommandDispatcher.parseMessage (/app/node_modules/discord.js-commando/src/dispatcher.js:238:21)
2020-09-30T23:08:24.272209+00:00 app[worker.1]: at CommandDispatcher.handleMessage (/app/node_modules/discord.js-commando/src/dispatcher.js:114:18)
2020-09-30T23:08:24.272210+00:00 app[worker.1]: at CommandoClient.<anonymous> (/app/node_modules/discord.js-commando/src/client.js:68:51)
2020-09-30T23:08:24.272210+00:00 app[worker.1]: at CommandoClient.emit (events.js:315:20)
2020-09-30T23:08:24.272211+00:00 app[worker.1]: at MessageCreateAction.handle (/app/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
2020-09-30T23:08:24.272212+00:00 app[worker.1]: at Object.module.exports [as MESSAGE_CREATE] (/app/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
2020-09-30T23:08:24.272213+00:00 app[worker.1]: at WebSocketManager.handlePacket (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
2020-09-30T23:08:24.272213+00:00 app[worker.1]: at WebSocketShard.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
Here is my main bot file:
index.js
const { Client } = require('discord.js-commando');
const { RichEmbed } = require('discord.js')
const path = require('path');
const prefix = (process.env.BOT_PREFIX);
const twitch_url = (process.env.TWITCH_URL);
const embed_color = (process.env.EMBED_COLOR);
const embed_img = (process.env.EMBED_IMG);
const embed_url = (process.env.EMBED_URL);
const avatar_url = (process.env.AVATAR_URL);
const thumbnail_url = (process.env.THUMBNAIL_URL);
const welcome_channel = (process.env.WELCOME_CHANNEL_NAME);
const member_role = (process.env._MEMBER_ROLE_NAME);
require('dotenv').config();
const client = new Client({
commandPrefix: prefix
})
client.registry
.registerDefaultTypes()
.registerGroups([
['admin', 'Administration'],
['mod', 'Moderation'],
['fun', 'Fun'],
['misc', 'Miscellanious'],
['util', 'Utility']
])
.registerDefaultGroups()
.registerDefaultCommands()
.registerCommandsIn(path.join(__dirname, 'commands'))
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}(${client.user.id})`)
client.user.setActivity(`${prefix}help`, {
type: "STREAMING",
url: twitch_url
})
});
client.on("guildMemberAdd", (member) => {
console.log(`New User "${member.user.username}" has joined "${member.guild.name}"`);
guildMember.addRole(guildMember.guild.roles.find(role => role.name === member_role));
let channel = member.guild.channels.find(c => c.name === welcome_channel);
const embed = new RichEmbed()
.setAuthor("Yuzuki Yukari", avatar_url)
.setUrl(embed_url)
.setColor(embed_color)
.setImage(embed_img)
.setThumbnail(thumbnail_url)
.setFooter("Yuzuki Yukari", avatar_url)
.addField("Welcome", `${member.user.username} has joined ${member.guild.name}`)
return channel.send(embed).catch(console.error);
});
client.on('guildMemberRemove', (member) => {
let channel = member.guild.channels.find(c => c.name === welcome_channel);
const embed = new RichEmbed()
.setAuthor("Yuzuki Yukari", avatar_url)
.setUrl(embed_url)
.setColor(embed_color)
.setImage(embed_img)
.setThumbnail(thumbnail_url)
.setFooter("Yuzuki Yukari", avatar_url)
.addField("Goodbye", `${member.user.username} has left ${member.guild.name}`)
return channel.send(embed).catch(console.error);
});
client.on('error', console.error)
client.login(process.env.BOT_TOKEN);
Here is my package.json file:
package.json
{
"name": "yuzuki",
"version": "1.0.0",
"description": "A Discord Moderation Bot built using Discord.js commando",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "Nimbi",
"license": "ISC",
"dependencies": {
"discord.js": "^12.0.1",
"discord.js-commando": "^0.10.0",
"path": "^0.12.7",
"snekfetch": "^4.0.4",
"sqlite": "^4.0.14",
"uws": "^100.0.1",
"nodemon": "^1.13.3",
"dotenv": "^8.2.0"
},
"engines": {
"node": "^12.0.0"
}
}
My dependencies and their versions can be seen in my package.json, however my node.js version is ^12.0.0, my discord.js version is ^12.0.1, and my discord.js-commando version is ^0.10.0 if that helps.
discord.js-commando#0.10.0 isn't compatible with discord.js#12. It's package.json specifies that Discord.js ^11.2.0 must be used.
The error is because Collection#filterArray was removed in v12, and therefore this.commands.filterArray is undefined and not a function in the Commando code.
You have 2 options:
Downgrade to Discord.js v11.
Use the master branch of discord.js-commando, which is compatible with Discord.js v12. However, this branch may be unstable and/or have bugs.
To use this, change "discord.js-commando": "^0.10.0" in your package.json to "discord.js-commando": "discordjs/Commando". See GitHub URLs in npm's package.json documentation for more details on this.

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;

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

Resources