Configuring Cypress.env() variable to an imported module file - javascript

I'm trying to set & config a new env variable in Cypress.io. In the file cypress/plugins/index.js, I have imported another file like so:
const { getBranch } = require('path/to/file/goes/here/getBranch');
Then, I'm trying to set the new env variable like so:
// cypress/plugins/index.js
module.exports = (on, config) => {
terminalReport.installPlugin(on);
const configuration = config;
configuration.env.injectMainBranchId = getBranch('develop');
// more code below...
However, this is not working. However, if I hardcode the value it does work:
configuration.env.injectMainBranchId = 'develop';
You see the result in the screenshot below:
This is the dummy content of getBranch module:
const getBranch = branch => {
return branch;
};
module.export = { getBranch };
What am I doing wrong?

Typo in getBranch:
const getBranch = branch => {
return branch;
};
module.export = { getBranch };
export should be changed to exports

Related

proxyquire Error: ENOENT: no such file or directory, scandir

Hello I am new to testing with mocha/chai/sinon and sequelize-test-helpers
Trying to use proxyquire to override the require but having issues
Getting this following error about the path:
Error: ENOENT: no such file or directory, scandir 'C:<local-directories-path>\ecommerce-pern-app\server\src\models'
I dont get why there is a src folder when I don't have a src folder at all I am using the proxyquire in the test file and its path is from the server directory would be:
server/specs/services/user-service.spec.js
"use strict";
const chai = require('chai');
const {match, stub, resetHistory, spy} = require('sinon');
const proxyquire = require('proxyquire');
const path = require('path');
const service = path.resolve('./services/userService.js')
var sinonChai = require("sinon-chai");
chai.should();
chai.use(sinonChai);
console.log(service)
const {makeMockModels, sequelize, dataTypes,} = require('sequelize-test-helpers');
describe('Idea Controller', function () {
const uid = '6a88e9b5-33a2-403f-ac3d-e86413ac101d'
const data = {
email: 'testface#test.com',
password: '123456',
is_admin: false,
first_name: 'Testy',
last_name: 'McTestface',
google_id: null,
facebook_id: null
}
describe('findAll()', function () {
it('Success case ', function () {
const mockResponse = () => {
const res = {};
res.json = stub().returns(res);
return res;
};
let res = mockResponse();
const User = {findAll: stub()};
const mockModels = makeMockModels({User});
Idea.findAll.resolves(data);
const UserService = proxyquire(service, {
"save": {}
});
UserService.findAll({}, res);
Idea.findAll.should.have.been.called; // passes
res.json.should.have.been.called; //fails
});
})
});
In the above code I am using the proxyquire like this:
const proxyquire = require('proxyquire');
const path = require('path');
const service = path.resolve('./services/userService.js')
const {makeMockModel} = require('sequelize-test-helpers');
const mockModels = makeMockModels({User});
const UserService = proxyquire(service, {
"../models": mockModels
});
As I am trying to use the path to find the server/service/userService.js file which is relatively located from the test file at ../../services/userService.js. I have got this bug that there is src folder there when I do not have a src directory at all even!
As the bug is saying:
Error: ENOENT: no such file or directory, scandir 'C:<local-directories-path>\ecommerce-pern-app\server\src\models'
Whatever I try about file path is not working I tried path.resolve, path.join and directly typing the path into it as like ../../services/userService.js
here is the
server/services/userService.js
const Models = require('../models');
const { User } = Models;
const save = async ({ id, ...data }) => {
const user = await User.findOne({ where: { uid: id } })
if (user) return await user.update(data)
return null
}
module.exports = save;
I just want the path to with proxyquire to work
What is this \src\models path from the error, I dont have a src/models path route at all!
This is a quote from sequelize-test-helpers's readme.
As a convenience, makeMockModels will automatically populate your mockModels with mocks of all of the models defined in your src/models folder (or if you have a .sequelizerc file it will look for the models-path in that). Simply override any of the specific models you need to do stuff with.
So you need to provide .sequelizerc file and define models-path.

How to export an object from a .js file to use it in main file

I have 2 files: bot.js and queue.js
In the second file i define a variable called queue using this code:
const { google } = require("googleapis");
const play = require('play-dl');
const lista = []
module.exports = { lista }
module.exports = {...
}
In the first file i try to import the object with this code:
require(`./commands/queue.js`)
console.log(lista)
But when
And i would like to be able to use its content in the first file
How can i do that? I've seen other answers and tried their methods but couldn't make it work
Ensure you export the object, then require it by deconstructing from the exports
Queue.js
const { google } = require("googleapis");
const play = require('play-dl');
const lista = []
module.exports = {
lista
}
Bot.js
const { lista } = require('path-to-queuejs-here');
console.log(lista)
// []

Dynamically export a module by reading all files in a directory in Node.js

So today i was trying read all default exports
from some directory which has index.js. Try to wrap it inside one object and export it back again. Is there a better way to handle this ?
export default (() => require('fs')
.readdirSync(__dirname)
.filter(fileName => !!/.js$/ig.test(fileName))
.map(fileName => fileName.split('.')[0])
.reduce((defaultExportObj, nextFileName) => {
try {
return {
...defaultExportObj,
[nextFileName]: require(__dirname + `/${nextFileName}`),
};
}catch(err) { throw err; }
}, {}))();
I guess i'd do something like this - not sure if this is better - w/e better is ^^
webpack: require.context
function expDefault(path, mode = "sync"){
const modules = {}
const context = require.context(path, false, /\.js$/, mode)
context.keys().forEach(file => {
const name = fileName.replace(/^.+\/([^/]+)\.js$/, "$1")
modules[name] = context(name).default
})
return modules
}
export default expDefault(__dirname)

How can I make static variable in `module.exports = class` in node.js

How can I initialize a static variable in module.exports = class in node.js.
Basically, what I'm trying to achieve is, if StaticVariable is null, Ill get data from a json file. Then store it in StaticVariable.
module.exports = class Config {
static fetch() {
if ( StaticVariable === null ) {
const fs = require('fs');
const data = fs.readFileSync('./config.json');
const config = JSON.parse(data);
StaticVariable = config;
}
return StaticVariable;
}
}
Function fetch() will be called several times so it is unnecessary to readFileSync every call.
Static-only class is an antipattern in JavaScript because a class is never instantiated.
In case there's a need to have a method that lazily loads JSON file, a plain object can be used. There's already such object in module scope, module.exports:
const fs = require('fs');
let StaticVariable;
exports.fetch = () => {
if ( StaticVariable == undefined ) { // not "=== null"
const data = fs.readFileSync('./config.json');
const config = JSON.parse(data);
StaticVariable = config;
}
return StaticVariable;
}
There may be no need to parse it manually because this could be handled by require('./config.json') one-liner and with more consistent relative paths.
In case JSON file can be eagerly loaded, this can be simplified to:
exports.config = require('./config.json');
If there's a need for Config class and it should access configuration object, it can refer to it, e.g.:
exports.Config = class Config {
constructor() {
this.config = deepClone(exports.config);
}
modify() {
// modify this.config
}
};
I can think of several ways to achieve what you are asking.
Saving it in a global variable
//initialise it here
var StaticVariable = null;
//however if you initialise it here, it makes more sense to just load it once
const fs = require('fs');
const data = fs.readFileSync('./config.json');
const config = JSON.parse(data);
StaticVariable = config;
module.exports = class Config {
static fetch() {
return StaticVariable;
}
}
Or just use require. Require will do the same thing what you want to do. It will read the file config.json, try to parse it as a valid json and it will do this only once.
module.exports = class Config {
static fetch() {
return require('./config.json');
}
}
Starting from (node 15.2.1) ES2020, static private class fields is supported. So from now on static class may not be anti pattern and you can instantiate a class using new keywords. ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
module.exports = class Config {
static #StaticVariable = null;
static fetch() {
if ( StaticVariable === null ) {
const fs = require('fs');
const data = fs.readFileSync('./config.json');
const config = JSON.parse(data);
StaticVariable = config;
}
return StaticVariable;
}
}
Where # sign means private more reference can be found in https://node.green, but still the easiest way is described in other answers
exports.config = require('./config.json');

How to call module with object Parameter in main file Index.js

I need to call module from main index.js File
Here is my module
const request = require('./rq.js');
const callback = require('./callback.js')
const url = `https://localhost.3000/${id}`;
request(url, callback)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
module.exports = page; //Tell me how to export all code from module
So here is my index.js file
const Methods = {
page: require('./page.js'),
}
module.exports = //What i need to code here?
File from what i give a call a module :
const main = require('./index.js');
main.page({id: 'id'})
.then(console.log);
So what I should change to call page.js file like that ?
Make the following changes to page.js since in your main file you expect a promise to be returned.
const request = require('./rq.js');
const callback = require('./callback.js')
function page({id}) {
const url = `https://localhost.3000/${id}`;
return request(url, callback)
}
module.exports = {page: page} //Tell me how to export all code from module
Make the following changes to Mehods.js
const Methods = {
page: require('./page.js').page,
}
module.exports = Methods;
Check if this works.

Categories

Resources