Node JS Error: Cannot find module './services' - node.js

I am trying to create stubs using sinon to run the test but its throwing error.
Its trying to find a module services and saying the module is not found but I have the services.js in the same folder as test. So I am not sure why its failing.
Can someone please advise what is wrong in the code.
1) the car-lookup controller "before each" hook for "should return filtered TAP response":
Error: Cannot find module './services' from 'C:\nodejsworkspace\olive\server\api\car-lookup'
at Function.module.exports [as sync] (node_modules\proxyquire\node_modules\resolve\lib\sync.js:40:15)
at Proxyquire._resolveModule (node_modules\proxyquire\lib\proxyquire.js:137:20)
at Proxyquire.<anonymous> (node_modules\proxyquire\lib\proxyquire.js:205:35)
at Array.reduce (<anonymous>)
at Proxyquire._withoutCache (node_modules\proxyquire\lib\proxyquire.js:204:6)
at Proxyquire.load (node_modules\proxyquire\lib\proxyquire.js:129:15)
at Context.<anonymous> (test\unit\server\api\car-lookup\car-lookup.controller.test.js:30:18)
controller = proxyquire('../../../../../server/api/car-lookup/car-lookup.controller.js', {
'./services': { taClient: new MockTaClient() }
});
});
Below is how I think the services are being exported from the car-lookup.controller.js
Below is car lookup controller.js
If you see in the first line it is trying to import services and services is not a direct js file. I have an index.js file in the ../../directory which is what the first line is referring to. Directory structure is also below. Please advise.
>server
> api
> car-lookup
>car-lookup.controller.js
>server
>services
>index.js
'use strict';
const services = require('../../services');
const { ApiError, ValidationError } = require('../../errors');
const AccountModel = require('../../models/account-model');
const lookupAccount = (req, res, next) => {
const retrieveAccount = (oktaToken) => {
return services.tapClient.retrieveAccount(req.body);
};
const sendResponse = (account) => {
res.send(new AccountModel(account));
};
const onError = (err) => {
next(err instanceof ValidationError ?
new ApiError(err, 400) :
err);
};
retrive()
.then(retrieveAccount)
.then(sendResponse)
.catch(onError);
};
module.exports = {
lookupAccount
};

Make sure you are exporting the file services properly

Related

Error: Module name "cassandra-driver" has not been loaded yet for context: _. Use require([])

I am using datastax cassandra-driver to make a database.
This is connect-database:
import { require } from "./requirejs.mjs";
export async function run() {
const { Client } = require("cassandra-driver");
const client1 = new Client({
cloud: {
get secureConnectBundle(){
return "secure-connect-amazonfeud.zip"}
},
credentials: {
get username(){
return "<my username>"},
get password(){
return "<my password>"}
},
});
await client1.connect();
const rs = await client1.execute("SELECT * FROM feud.users");
const results = await client1.execute("update feud.users set score=250 where id=1")
console.log(rs['rows'][0])
console.log(`Your cluster returned ${rs.rowLength} row(s)`);
await client1.shutdown();
}
This is main.js:
import { run } from "./connect-database.mjs";
run()
When I run connect-database.mjs, it works, but when I run main.js it gives me error "Uncaught Error Error: Module name "cassandra-driver" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded"
When I change the format to be require[], it says "Uncaught TypeError TypeError: Client is not a constructor"
Please help
If you're using a custom require in order to require cassandra-driver, you don't need to do that. Client function is exposed using module.exports in cassandra-driver so you can use a simple import.
An example that worked for me:
cassandraDriverTest.mjs
import { Client } from 'cassandra-driver';
import { inspect } from 'util';
const client = new Client({
contactPoints: ['cp'],
localDataCenter: 'dc1',
keyspace: 'ks'
});
const query = '<query>';
client.execute(query)
.then(result => console.log('User with email %s', result.rows[0].some_data,));
console.log(inspect(client));

TypeORM and MongoDB and Repositories: Cannot read property 'prototype' of undefined

I'm trying implement TypeORM with MongoDB using repositories. However, when I try to make use of repositories to manage the database, using the same structure as in this repository, things go a bit sideways. I'm getting the following error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'prototype' of undefined
I have tried the following code:
import { Request, Response } from 'express';
import { getMongoRepository } from "typeorm";
import Task from "../models/Task";
export default class TasksController {
async listAll(request: Request, response: Response): Promise<Response> {
const tasksRepository = getMongoRepository(Task);
try {
const tasks = await tasksRepository.find();
return response.status(200).json({ "items": tasks });
} catch (err) {
return response.status(400).json({
message: err.message,
});
}
}
}
I know the error refers to implementing the .find() method. I have even managed to fetch the data, using a suggestion from this post replacing:
const tasks = await tasksRepository.find();
with
const tasks = await tasksRepository.createCursor(tasksRepository.find()).toArray();
but I still get the above mentioned error.
Anyone understands what's going on?
I have also managed to save data directly to the database through the use of the following script:
server.ts
import express from 'express';
import { createConnection } from 'typeorm'
const app = express();
const port = 3333;
createConnection();
app.use(express.json());
app.post('/tasks', (async (request, response) => {
const { item } = request.body;
task.item = item;
const task = new Task();
(await connection).mongoManager.save(task);
return response.send(task);
}))
app.listen(port, () =>
console.log(`Server running on port ${port}`)
);
TypeORM is not support mongodb v4.
https://github.com/nestjs/nest/issues/7798
You can use 3.7.0 instead.
I submitted a pull requests to resolve this. https://github.com/typeorm/typeorm/pull/8412 if anyone is looking for a workaround in the meantime.

How correctly require in Jest file ? (with a module pattern js file)

Probably a stupid question
I start using JEST for testing.
I have my js app :
var app={ init:function{ //some code}, ... }
module.exports = app;
And my app.test.js :
const {app} = require('../js/index.js')
test('type of variable', () => {
expect(typeof app.someFunction(app.someVar)).toBe("'number");
});
And I have the classic error :
TypeError: Cannot read property 'someFunction' of undefined
It seem very stupid, but I never understand clearly these require on client side...
It work perfectly with the Jest getStarted example
My arbo is
-js
----index.js
-tests
----app.text.js
module.exports = app
The above line returns object {}, and you are trying to pick app from object in your destructing line var {app}
Remove {}
const app = require('../js/index.js')
test('type of variable', () => {
expect(typeof app.someFunction(app.someVar)).toBe("'number");
});

NUXT: Module not found: Error: Can't resolve 'fs'

I'm starting out with vue and nuxt, I have a project using vuetify and I'm trying to modify the carousel component to dynamically load images from the static folder. So far I've come up with:
<template>
<v-carousel>
<v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
</v-carousel>
</template>
<script>
function getImagePaths() {
var glob = require("glob");
var options = {
cwd: "./static"
};
var fileNames = glob.sync("*", options);
var items = [];
fileNames.forEach(fileName =>
items.push({
'src': '/'+fileName
})
);
return items;
}
export default {
data() {
return {items :getImagePaths()};
}
};
</script>
When I test this I see:
ERROR in ./node_modules/fs.realpath/index.js
Module not found: Error: Can't resolve 'fs' in '....\node_modules\fs.realpath'
ERROR in ./node_modules/fs.realpath/old.js
Module not found: Error: Can't resolve 'fs' in ....\node_modules\fs.realpath'
ERROR in ./node_modules/glob/glob.js
Module not found: Error: Can't resolve 'fs' in '....\node_modules\glob'
ERROR in ./node_modules/glob/sync.js
Module not found: Error: Can't resolve 'fs' in '.....\node_modules\glob'
googling this I see a bunch of references like https://github.com/webpack-contrib/css-loader/issues/447.
These suggest that you have to midify the webpack config file with something like:
node: {
fs: 'empty'
}
I know very little about webpack. I found https://nuxtjs.org/faq/extend-webpack/ , but am not sure how to modify the webpack config file in this case.
How do I do this?
You can't use NodeJs specific module on browser.
To solve your issue, you can create an API using Nuxt server middleware. The code below, inspired by https://github.com/nuxt-community/express-template.
Create a file, index.js in api/index.js. Then fill it with:
const express = require('express')
// Create express instance
const app = express()
// Require API routes
const carousel = require('./routes/carousel')
// Import API Routes
app.use(carousel)
// Export the server middleware
module.exports = {
path: '/api',
handler: app
}
Create carousel.js in api/routes/carousel.js. Then fill it with:
const { Router } = require('express')
const glob = require('glob')
const router = Router()
router.get('/carousel/images', async function (req, res) {
const options = {
cwd: './static'
}
const filenames = glob.sync('*', options)
let items = [];
filenames.forEach(filename =>
items.push({
'src': '/'+filename
})
);
return res.json({ data: items })
})
module.exports = router
Register your server middleware in nuxt.config.js
module.exports = {
build: {
...
},
serverMiddleware: [
'~/api/index.js'
]
}
Call the api in your page / component. I assume you're using Axios here (axios-module).
<script>
export default {
async asyncData ({ $axios }) {
const images = (await $axios.$get('/api/carousel/images')).data
return { images }
}
}
</script>
I know this is an old question, but it may be helpful for someone to disable fs in their browser.
Like this:
nuxt.config.js
build: {
extend (config, { isDev, isClient }) {
config.node= {
fs: 'empty'
}
// ....
}
},
Add this in your nuxt-config.js:
build: { extend (config, { isDev, isClient }) {
config.node = {
fs: 'empty'
}
// ....
}},

How to mock module function using proxyquire

I need to mock 'mkdirp-promise' node module which exposes a constructor function as below
mkdirpPromise(dirPath)
.then(() => {
console.log('ABCDEFGH');
resolve(dirPath);
})
.catch((error) => {
console.log('HeABCDEFGHre');
const details = error.message;
const err = customError.failed_create_downloads_directory()
.withDetails(details);
reject(err);
});
Im able to mock it using proxiquire as below for the first time:-
let mkdirpPromiseMock = sinon.stub().rejects();
const sthreeDownloadMock =
proxyquire('./../../modules/sThreeDownload', {
joi: joiMock,
fs: fsMock,
'#monotype/core-error': {
errors: {
ApiError: customErrorMock,
},
},
'aws-sdk': awsSDK,
'mkdirp-promise': mkdirpPromiseMock,
path: pathMock,
});
Now i want to override mkdirpPromiseMock in 2nd test case with
mkdirpPromiseMock = sinon.stub().resolves();
which im not able to. Any help is appreciated.
Proxyquire is not compatible with jest.
You need to use a mocking library like rewiremock.
Please have a look at this answer which goes into detail.
REPL example

Resources