Node Config: How to prevent use of custom-environment-variables.json for Jest tests
I have a couple of Jest tests running in my NodeJS application that is configured to extract a dbConnString
setting from config, using node-config.
I have a test.json file that specifies a dbConnString
value (this is the one I expect the Jest tests to use). I also have a custom-environment-variables.json
file that contains mappings of keys to environment variables that contain the actual connection strings to use for my dev environment.
What I'm finding is that the Jest tests are using the said environment variables mapped in custom-environment-variables.json
. How can I force the Jest tests to use the dbConnString
setting defined in test.json
?
I have confirmed that in a test the process.env.NODE_ENV
does return test
.
See also questions close to this topic
-
clear cart from session , and after logging it to console i get empty array but when visit cart view i still get cart items
I am working on e-commerce project , after checkout i wrote a code that deletes the cart items , and just to make sure i console.log(req.session.cart), and it shows an empty array means that session.cart is empty , but then i redirect user to home page , but then on home page i still get cart and its items , how to solve this problem? thanks .
this is how i cleared my cart its working fine!
order.save().then((r) => { // console.log(r) console.log("after checkout") for (let index = 0; index < req.session.cart.length; index++) { req.session.cart.splice(index) } console.log("Cart after clearing items ") console.log(req.session.cart
but if I revisit my cartView route i still get cart adn its items
router.get('/viewCarts', (req, res) => { console.log("cart items ",req.session.cart) catSchema.find({}).then((categories) => { // console.log(req.session.cart) res.render('../views/cartView/cartView.ejs', { layout: '../views/welcome/welcomeHeader.ejs', options: 'BUY', title: 'MY CART', cat: categories, cart:req.session.cart }); }); });
-
Stripe POST request with Authentication code
Server Side:
// Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys const Stripe = require('stripe'); const stripe = Stripe('sk_test_xxxxxx'); const response = await stripe.oauth.token({ grant_type: 'authorization_code', code: 'ac_123456789', }); var connected_account_id = response.stripe_user_id;
Client Side:
How can i create a POST request to receive the
connected_account_id
Documentation info: https://stripe.com/docs/connect/oauth-standard-accounts
-
I'm using Windows 10 and I can't seem to use set the environment variable on nodejs on my terminal
I'm a beginner to nodejs. I created two json files with different names and mail.host. The first one is called development.json
{ "name": "My Express App - Development", "mail": { "host": "dev-mail-server" } }
and the other one is production.json{ "name": "My Express App - Production", "mail": { "host": "prod-mail-server" } }
after using executing this code below on my index.js, the terminal prints the same output even after using set NODE_ENV="production" in the terminal. What seems to be the problem in my code? Thank you so much!console.log(
Application Name: ${config.get('name')}
) console.log(Mail Server: ${config.get('mail.host')}
) -
Adjacent sibling selector with Enzyme dose NOT work
I have html like below:
<input type ="text" id="textInput-FirstName" /> <div class="col error">warning Message</div>
I am trying to get the "warning Message", so I use the code below:
expect(wrapper.find('#textInput-FirstName + div').text()).toBe('warning Message');
But I got an error in the console saying "Method “text” is meant to be run on 1 node. 0 found instead."
I use the $('input#textInput-FirstName + div') in the console in chrome browser and it can find the node. I have no idea why it doesn't work with enzyme. Could anyone tell me is there something wrong? I use “expect(wrapper.find('.error').text()).toBe('warning Message')” and it works fine, but I need to use "input#textInput-FirstName + div" because I have another familiar nodes.
I use "react": "^16.9.0", "jest": "^24.9.0", "enzyme": "^3.11.0"
-
Ts and jest Best way to test routes
I'm starting with jest, and I'm trying to test a route, but I don't know what is the best way to do this, well the way I did it with docker, I go up the docker and start the server express but in my test i create it again and i'm getting my port already in use:
● Hello Word Route › should return a json with value: hello word listen EADDRINUSE: address already in use :::8080 50 | 51 | public start(): void { > 52 | this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => {
I have the following bootstrap to start my server:
class ApplicationServer implements Server { private express: Application; private logger: LoggerProvider; private server: http.Server constructor(logger: LoggerProvider) { this.express = express(); this.logger = logger; } public getExpress(): Application { return this.express } public getLogger():LoggerProvider { return this.logger; } public getServer():http.Server { return this.server; } public async close(): Promise<void> { try { this.logger.log(`info`, `closing the http server`, {}) this.server.close() this.logger.log(`info`, `Http server successfully closed`, {}) this.logger.log(`info`, `closing the database`, {}) await closeDB(); this.logger.log(`info`, `Database successfully closed`, {}) } catch (error) { this.logger.log(`error`, error.message, error) } } public async init(): Promise<void> { setupStaticFiles(this.express); setupMiddlewares(this.express); setupRoutest(this.express, this.logger); await connectDB(this.logger) } public start(): void { this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => { this.logger.log( `info`, `Server listening on port: ${process.env.APP_PORT || 8080}`, {} ); }); } } export default ApplicationServer;
factory:
export const SetupServer = (): Server => { const logger = new adptLogger({}) return new ApplicationServer(logger) }
start:
(async () => { const server = SetupServer(); try { await server .init() .then(() => server.start()) } catch (error) { console.error(error) server.getLogger().log(`error`, error.message, error) process.exit() } })();
and this is my test::
describe("Hello Word Route", () => { let server= {} as Server; beforeAll(async () => { server = SetupServer(); await server.init(); server.start(); }); afterAll(async () => { }); it("should return a json with value: hello word", async () => { await request(server.getExpress()) .post("api/hello-word") .send({hello: 'hello word'}) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); }); });
I would like to know what is the best practice to take in this situation to perform route tests my test fail:
Hello Word Route › should return a json with value: hello word listen EADDRINUSE: address already in use :::8080 50 | 51 | public start(): void { > 52 | this.server = this.express.listen(Number(process.env.APP_PORT) || 8080, () => { | ^ 53 | this.logger.log( 54 | `info`, 55 | `Server listening on port: ${process.env.APP_PORT || 8080}`, at Function.listen (node_modules/express/lib/application.js:618:24) at ApplicationServer.start (src/application/infra/app.ts:52:32) at Object.<anonymous> (src/application/routes/hello-word-routes.test.ts:11:12) (node:113) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) (Use `node --trace-warnings ...` to show where the warning was created) (node:113) 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 terminate 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) (node:113) [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.
-
Simulate Width to Test Responsive React Components
There is a
Drawer
and aButton
which opens theDrawer
. TheButton
and theDrawer
only appear in the DOM when the window width is less than 600.This is the
Drawer
andButton
code.<Hidden smUp> <Button className={classes.button} variant="outlined" color="secondary" endIcon={<Menu />} onClick={toggleDrawer(true)} data-testid="DrawerMenuButton" > Menu </Button> <SwipeableDrawer anchor="left" open={open} onClose={toggleDrawer(false)} onOpen={toggleDrawer(true)} disableDiscovery data-testid="Drawer" > <div className={classes.list}> <List data-testid="DrawerMenuList"> {drawerItems.map(({ icon: Icon, label, onClick }, index) => ( <ListItem key={index} button {...{ onClick }}> <ListItemIcon> <Icon /> </ListItemIcon> <ListItemText primary={label} /> </ListItem> ))} </List> </div> </SwipeableDrawer>
When running
screen.debug()
during tests, this is the output<body> <div /> </body>
meaning that the width is not within the range for the components to appear.
How can the right width be set?