We have an amd/requirejs based web app. We came to a point to add a unit testing to our code. Googling returned that squireJs is best amd-require based mocking library. after installing, The problem is that we cant resolve the squirejs dependency. The issue seems so basic but we tried with both Mocha and Jasmine to use it, though it seems something we are forgetting to configure:
our js that we want to test looks basically like:
define(function employeeAndTagsPage(require) {
var global = require('common/global');
var customMessageWindow = require('../../customMessageWindow/customMessageWindow');
var currentTab;
var navigate = null;
// and other BL
});
Package.json:
{
"name": "jasmine.test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"devDependencies": {
"amd-loader": "0.0.8",
"jasmine-node": "^3.0.0",
"requirejs": "^2.3.6",
"squirejs": "^0.2.1"
}
}
Jasmine_examples PlayerSpec.js:
describe("Player", function () {
require('amd-loader');
var Player = require('../../lib/jasmine_examples/Player');
var Song = require('../../lib/jasmine_examples/Song');
var requirejs = require('requirejs');
var squire = requirejs('squirejs'); // here it fails
var player, song, mock;
beforeEach(function() {
player = new Player();
song = new Song();
mock = new squire();
});
//unit tesitng
});
The error we are getting:
ReferenceError: requirejs is not defined
Stack:
at <Jasmine>
at getContext (c:\Synel\TESTS\eHarmonyNew-Jasmine\eHarmony\App\Test\node_modules\squirejs\src\Squire.js:58:5)
at Squire.configure (c:\Synel\TESTS\eHarmonyNew-Jasmine\eHarmony\App\Test\node_modules\squirejs\src\Squire.js:107:15)
The squirejs library code can be found here:
https://github.com/iammerrick/Squire.js/blob/master/src/Squire.js
What is the reason of the library being failed ? What we are forgetting? Any assist or reccomendation is appraciated
Related
I am new to Node.js. I want to create mysql connection and insert data into the database and access it later. I installed, node.js, then using npm installed 'mysql' and 'faker'.
Using node.js I successfully connected to mysql, created database and tables(code in mysql1.js in the folder NODE-JS).
Then I went ahead to create fake data (code in fake_data.js) to insert into the table.
screenshot of vscode
var faker = require("faker");
let first_name = faker.name.firstName();
let last_name = faker.name.lastName();
console.log(Employee: ${prefix} ${first_name} ${last_name} ${suffix});
But this time I got error
code: 'MODULE_NOT_FOUND',
path: 'D:\\DATABASES\\NODE-JS\\node_modules\\faker\\package.json',
requestPath: 'faker'
package.json file contains the following dependencies
{
"dependencies": {
"faker": "^6.6.6",
"mysql": "^2.18.1"
},
"name": "node-js",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
I tried,
var faker = require("./faker");
even then it throws error
please help me to rectify the problem. thanks
The owner of faker deleted it from GitHub at v6.6.6
You can see that here:
https://github.com/marak/Faker.js/
So it is up to the community to complete it
The new repository:
https://github.com/faker-js/faker
This is the official, stable fork of Faker.
Installation
Please replace your faker dependency with #faker-js/faker.
npm install #faker-js/faker --save-dev
Node.js
const { faker } = require('#faker-js/faker');
Hi I am starting with Node Js and tried a code as per the documentation over here. I did everything accordingly but I am getting below error.
const Bumblebee = require('bumblebee-hotword');
^
SyntaxError: Identifier 'Bumblebee' has already been declared
at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
at async link (node:internal/modules/esm/module_job:48:21)
Here is the index.js code
import Bumblebee from "bumblebee-hotword";
const Bumblebee = require('bumblebee-hotword');
let bumblebee = new Bumblebee();
// set path to worker files
bumblebee.setWorkersPath('/bumblebee-workers');
// add hotword
bumblebee.addHotword('jarvis');
// set sensitivity from 0.0 to 1.0
bumblebee.setSensitivity(1.0);
bumblebee.on('hotword', function(hotword) {
// YOUR CODE HERE
console.log('hotword detected:', hotword);
});
bumblebee.start();
And here is the package.json
{
"name": "Hotword_template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bumblebee-hotword": "^0.2.1"
}
}
Also the required directory "bumblebee-workers" is in the same directory.
I don't know where I am doing wrong, any help is highly appreciated!!
Look at these two lines, you are importing and using constant variable of same name.
import Bumblebee from "bumblebee-hotword";
const Bumblebee = require('bumblebee-hotword');
Changing the name of const variable can solve your problem.
I try to build my first npm package, but now I got stuck.
I want to load from my package a config file that is located in the root of my test-project
I used "npm link my-package" to install it locale for testing (if this important)
This is my folder structure
- my-package
- test-project
- node-modules
- my-package (npm link)
- config.json
The package is a vuejs app that should start a server and serve a page
I run this script from my test-project
"scripts": {
"generatePage": "npm explore my-package -- npm run serve"
},
script from my package
"scripts": {
"serve": "node readFile.js & vue-cli-service serve"
},
my-package/readFile.js
file_path = path.join(process.cwd(), 'config.json')
console.log('file_path', file_path)
If I'm running my script I get this path /Users/name/work/my-package/config.json but I need /Users/name/work/test-project/config.json
How do I get the correct path?
When you write a library that will be used by another code base you cannot be sure where exactly NPM or yarn (or whatever package manager you choose) will install your library. It may be directly in node_modules but it may be nested depending upon the use case. However, as indicated by the stackoverflow answer here the process.main.filename variable will tell us exactly where the main process that is calling us lives. We can use this value to determine where the config file you want to read exists.
Here is some example code:
The config-lib library reads a configuration.
index.js file:
const fs = require("fs");
const path = require("path");
const promisify = require("util").promisify;
const readFilep = promisify(fs.readFile);
module.exports = async function loadConfig(filename = "config.json") {
const configPath = path.resolve(
path.dirname(require.main.filename),
filename
);
console.log("(load-config lib) Config Path: " + configPath);
try {
const data = await readFilep(configPath, "utf8");
return JSON.parse(data);
} catch (err) {
console.log(err);
}
};
This library has a simple package.json
{
"name": "config-lib",
"version": "1.0.0",
"description": "I read a config",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Some Cool Guy <somecoolguy#example.com>",
"license": "MIT"
}
Now the project itself requires this library. Here is the projects package.json
{
"name": "project",
"version": "1.0.0",
"description": "I am the project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Some Other Cool Guy <someoneelse#example.com>",
"license": "MIT",
"dependencies": {
"config-lib": "file:../lib"
}
}
(The config-lib library in this example was loaded from a local folder.)
The config-lib library requires me, in my project, to create a configuration file called config.json (BTW... name it something more specific to your library as to not collide with a local project configuration if they have one).
Here is an example config.json:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Finally, in my project I can use the config-lib library to read my configuration file:
const configLib = require("config-lib");
(async () => {
console.log("Reading config");
const data = await configLib();
console.log("Here is my config: " + JSON.stringify(data));
console.log("key1 value: " + data.key1);
})();
Hi everyone I'm beginner in nodejs .I want to test some basic functionality in my code.I m using JEST testing framework.In the command prompt I used npm test I could not test my code it shows
npm ERR! Test failed. Can anyone solve this issue? Thanks in advance...
lib.test.js:
const lib=require('../lib.js');
describe('absolute',()=>{
it('It should return positive number if given number is positive',()=>{
const result=lib.absolute(1);
expect(result).toBe(1);
});
it('It should return positive number if given number is negative',()=>{
const result=lib.absolute(-1);
expect(result).toBe(1);
})
it('It should return zero if given number is zero',()=>{
const result=lib.absolute(0);
expect(result).toBe(1);
});
});
lib.js:
// Testing numbers
module.exports.absolute = function(number) {
if (number > 0) return number;
if (number < 0) return -number;
return 0;
}
package.json:
{
"name": "testing-demo",
"version": "1.0.0",
"description": "",
"main": "db.js",
"directories": {
"test": "tests"
},
"dependencies": {},
"devDependencies": {
"jest": "^22.2.2"
},
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC"
}
I'm guessing the error you are seeing is
SecurityError: localStorage is not available for opaque origins
The default test environment for Jest is a browser-like environment provided by jsdom, which is required for testing code like React applications that are designed to run in the browser.
If you are going to use jsdom as the test environment then you need to set testURL in the Jest configuration, otherwise you will get the error seen above.
If your code is designed to run on node and you don't need a browser-like environment then you can set your test environment to be node.
The easiest way to do that in your case is to pass it as a command line argument to jest in your package.json:
"scripts": {
"test": "jest --env=node"
},
I'm recently updating my cloud functions to TypeScript after the talks on the FirebaseSummit of this year.
All my code looks quite cool, but I'm having some problems trying to recover the types of Firestore API, such QuerySnapshot , DocumentReference...
async function getEventsMadeByUser(userId: string): Promise<FirebaseFirestore.DocumentSnapshot[]> {
const eventsMadeByUserQuery = await instance.collection('PrivateUserData')
.doc(userId).collection(EVENTS)
.where('interactionUser', '==', userId).get();
return eventsMadeByUserQuery.docs;
}
Right now my IDE (WebStorm) is not getting the types for FirebaseFirestore. This is how my package.json looks:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"firebase-admin": "^5.4.3",
"firebase-functions": "^0.7.2"
},
"devDependencies": {
"#types/express": "^4.0.37",
"typescript": "^2.3.2"
},
"scripts": {
"build": "tsc",
"watch": "tsc --watch",
"deploy": "tsc && firebase deploy --only functions"
},
"main": "build/index.js",
"private": true
}
I have already tried to add #firebase-firestore and nothing, it's not working. What is the right dependency to achieve this?
I finally figured it out! The firebase-admin module is just a simple wrapper that initializes Firestore for you. To get the real Firestore, add "#google-cloud/firestore": "^0.9.0" to your package.json. You can admire those beautiful types here: https://github.com/googleapis/nodejs-firestore/blob/master/types/firestore.d.ts.
import { DocumentData } from '#firebase/firestore-types'
I figured out that you can get the types directly from firebase-admin without adding additional packages:
import { firestore } from 'firebase-admin'
const iAmConsumingDB = (db: firestore.Firestore) => {
// do something
}
const iAmConsumingADocumentReference = (reference: firestore.DocumentReference) => {
// do something
}