Prisma Jest tests return undefined - jestjs

I'm transitioning from TypeORM to Prisma. All of my until test Prisma functions are returning undefined. I'm using dependency injection from https://www.prisma.io/docs/guides/testing/unit-testing
const mockCtx2 = createMockContext()
const ctx2 = mockCtx2 as unknown as Context
console.log("createDummyUser")
console.log(ctx2)
console.log(ctx2.prisma)
console.log(ctx2.prisma.users)
returns
console.log
{ prisma: { _isMockObject: true } }
at test/userService.test.ts:889:15
console.log
{ _isMockObject: true }
at test/userService.test.ts:890:15
console.log
[Function: mockConstructor] {
_isMockFunction: true,
getMockImplementation: [Function (anonymous)],
mock: [Getter/Setter],
mockClear: [Function (anonymous)],
mockReset: [Function (anonymous)],
mockRestore: [Function (anonymous)],
mockReturnValueOnce: [Function (anonymous)],
mockResolvedValueOnce: [Function (anonymous)],
mockRejectedValueOnce: [Function (anonymous)],
mockReturnValue: [Function (anonymous)],
mockResolvedValue: [Function (anonymous)],
mockRejectedValue: [Function (anonymous)],
mockImplementationOnce: [Function (anonymous)],
mockImplementation: [Function (anonymous)],
mockReturnThis: [Function (anonymous)],
mockName: [Function (anonymous)],
getMockName: [Function (anonymous)],
calledWith: [Function (anonymous)],
_isMockObject: true
}
All of my requests return undefined
const allUsers1 = await ctx2.prisma.users.findMany()
console.log(allUsers1)
UPDATE
import prisma from '../client'
const u = await prisma.users.findMany()
console.log("****")
console.log(u)
client.ts
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
export default prisma

Related

How to mock value mongoose find with method lean and not using lean in Jest Node JS

I want to ask about mock mongoose find.
Let's say I have 2 method mongoose model find like this :
let resultA = await ModelA.find()
and let resultB = await ModelA.find().lean().
These 2 is called in different utils. I tried with mockImplementation like this :
mockMongooseFind.mockImplementation(() => {
return {
lean: jest.fn().mockResolvedValue(resultValueMockFind),
};
});
I
t only work when called method lean but not work when not called method lean.
The result with lean is proper data. But when get the result when not use lean is will be like this :
{ lean:
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockRestore: [Function],
mockReturnValueOnce: [Function],
mockResolvedValueOnce: [Function],
mockRejectedValueOnce: [Function],
mockReturnValue: [Function],
mockResolvedValue: [Function],
mockRejectedValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockName: [Function],
getMockName: [Function] } }.
How I make the proper mock for this case?
Get the better function for mock the mongoose method

Unable to retrieve multiple values from database

The following data exists in the database:
[
{
"_id": {
"$oid": "628c787de53612aad30021ab"
},
"ticker": "EURUSD",
"dtyyyymmdd": "20030505",
"time": "030000",
"open": "1.12161",
"high": "1.12209",
"low": "1.12161",
"close": "1.12209",
"vol": "561",
"id": 1
},
{
"_id": {
"$oid": "628c787de53612aad30021ac"
},
"ticker": "EURUSD",
"dtyyyymmdd": "20030505",
"time": "030100",
"open": "1.12206",
"high": "1.1225",
"low": "1.12206",
"close": "1.1225",
"vol": "1223",
"id": 2
},
{
"_id": {
"$oid": "628c787de53612aad30021ad"
},
"ticker": "EURUSD",
"dtyyyymmdd": "20030505",
"time": "030200",
"open": "1.12238",
"high": "1.12247",
"low": "1.12225",
"close": "1.12231",
"vol": "816",
"id": 3
}
]
If you pull out a single value, for example, through the command:
.findOne({id: 1});
There are no problems and everything works fine.
The problem occurs when getting multiple values from the base - for example:
.find({ticker:"EURUSD"}));
Such a command produces the following output:
FindCursor {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false,
[Symbol(topology)]: Topology {
_events: [Object: null prototype] {
connectionPoolCreated: [Function (anonymous)],
connectionPoolClosed: [Function (anonymous)],
connectionCreated: [Function (anonymous)],
connectionReady: [Function (anonymous)],
connectionClosed: [Function (anonymous)],
connectionCheckOutStarted: [Function (anonymous)],
connectionCheckOutFailed: [Function (anonymous)],
connectionCheckedOut: [Function (anonymous)],
connectionCheckedIn: [Function (anonymous)],
connectionPoolCleared: [Function (anonymous)],
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
topologyDescriptionChanged: [Function (anonymous)],
error: [Function (anonymous)],
timeout: [Function (anonymous)],
close: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)]
},
_eventsCount: 25,
_maxListeners: undefined,
bson: [Object: null prototype] {
serialize: [Function: serialize],
deserialize: [Function: deserialize]
},
s: {
id: 0,
options: [Object: null prototype],
seedlist: [Array],
state: 'connected',
description: [TopologyDescription],
serverSelectionTimeoutMS: 30000,
heartbeatFrequencyMS: 10000,
minHeartbeatFrequencyMS: 500,
servers: [Map],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
credentials: undefined,
clusterTime: undefined,
connectionTimers: Set(0) {},
detectShardedTopology: [Function: detectShardedTopology],
detectSrvRecords: [Function: detectSrvRecords]
},
[Symbol(kCapture)]: false,
[Symbol(waitQueue)]: Denque {
_head: 2,
_tail: 2,
_capacity: undefined,
_capacityMask: 3,
_list: [Array]
}
},
[Symbol(namespace)]: MongoDBNamespace { db: 'Trading', collection: 'EUR/USD' },
[Symbol(documents)]: [],
[Symbol(initialized)]: false,
[Symbol(closed)]: false,
[Symbol(killed)]: false,
[Symbol(options)]: {
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined,
maxStalenessSeconds: undefined,
minWireVersion: undefined
},
fieldsAsRaw: {},
promoteValues: true,
promoteBuffers: false,
promoteLongs: true,
serializeFunctions: false,
ignoreUndefined: false,
bsonRegExp: false,
raw: false,
enableUtf8Validation: true
},
[Symbol(filter)]: { ticker: 'EURUSD' },
[Symbol(builtOptions)]: {
raw: false,
promoteLongs: true,
promoteValues: true,
promoteBuffers: false,
ignoreUndefined: false,
bsonRegExp: false,
serializeFunctions: false,
fieldsAsRaw: {},
enableUtf8Validation: true,
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined,
maxStalenessSeconds: undefined,
minWireVersion: undefined
}
}
}
Question:
Why is this happening and how to get the needed result?
find return value is a cursor in nodejs, there are several ways on how you can use it to access the data, you can read about them here
The easiest way is to use the .toArray() cursor function which just converts the cursor to an array of documents, like so:
const results = await db.collection.find({ticker:"EURUSD"})).toArray();

How to display all entries from my mongodb atlas database using nodejs?

This is my current code to find all entries from MongoDB atlas.
const { MongoClient } = require("mongodb");
const client = new MongoClient(url);
const dbName = "Chats";
const db = client.db(dbName);
const col = db.collection("Users");
app.post('/chat/enter', (req, res) => {
let newmsg = new DataClass(req.body.name, req.body.textChat);
add(newmsg).catch(console.dir);
res.render(path.join(__dirname + "/index.ejs"),{texts:texts});
})
async function add(x) {
try{
await client.connect();
await col.insertOne({"name":x.name,"textChat":x.msg});
}catch (e) {
console.log(e);
}
}
async function find(){
try{
await client.connect();
const a= await col.find({});
console.log(a);
}catch(e){
console.log(e);
}
}
find();
I want to display all the entries from my atlas database but so far I am getting this gibberish. This problem only arises when I use the find keyword or the output is more than one. findOne is working properly.
The output from the terminal is -
FindCursor {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false,
[Symbol(topology)]: Topology {
_events: [Object: null prototype] {
topologyDescriptionChanged: [Array],
connectionPoolCreated: [Function (anonymous)],
connectionPoolClosed: [Function (anonymous)],
connectionCreated: [Function (anonymous)],
connectionReady: [Function (anonymous)],
connectionClosed: [Function (anonymous)],
connectionCheckOutStarted: [Function (anonymous)],
connectionCheckOutFailed: [Function (anonymous)],
connectionCheckedOut: [Function (anonymous)],
connectionCheckedIn: [Function (anonymous)],
connectionPoolCleared: [Function (anonymous)],
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
error: [Function (anonymous)],
timeout: [Function (anonymous)],
close: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)]
},
_eventsCount: 25,
_maxListeners: undefined,
bson: [Object: null prototype] {
serialize: [Function: serialize],
deserialize: [Function: deserialize]
},
s: {
id: 0,
options: [Object: null prototype],
seedlist: [Array],
state: 'connected',
description: [TopologyDescription],
serverSelectionTimeoutMS: 30000,
heartbeatFrequencyMS: 10000,
minHeartbeatFrequencyMS: 500,
servers: [Map],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
credentials: [MongoCredentials],
clusterTime: [Object],
connectionTimers: Set(0) {},
detectShardedTopology: [Function: detectShardedTopology],
detectSrvRecords: [Function: detectSrvRecords],
srvPoller: [SrvPoller]
},
[Symbol(kCapture)]: false,
[Symbol(waitQueue)]: Denque {
_head: 3,
_tail: 3,
_capacity: undefined,
_capacityMask: 3,
_list: [Array]
}
},
[Symbol(namespace)]: MongoDBNamespace { db: 'Chats', collection: 'Users' },
[Symbol(documents)]: [],
[Symbol(initialized)]: false,
[Symbol(closed)]: false,
[Symbol(killed)]: false,
[Symbol(options)]: {
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined,
maxStalenessSeconds: undefined,
minWireVersion: undefined
},
fieldsAsRaw: {},
promoteValues: true,
promoteBuffers: false,
promoteLongs: true,
serializeFunctions: false,
ignoreUndefined: false,
bsonRegExp: false,
raw: false,
enableUtf8Validation: true
},
[Symbol(filter)]: {},
[Symbol(builtOptions)]: {
raw: false,
promoteLongs: true,
promoteValues: true,
promoteBuffers: false,
ignoreUndefined: false,
bsonRegExp: false,
serializeFunctions: false,
fieldsAsRaw: {},
enableUtf8Validation: true,
writeConcern: WriteConcern { w: 'majority' },
readPreference: ReadPreference {
mode: 'primary',
tags: undefined,
hedge: undefined,
maxStalenessSeconds: undefined,
minWireVersion: undefined
}
}
}
Try to initialize the database connection in a separate method:
const { MongoClient } = require("mongodb");
const connectDB = async () => {
try {
const client = new MongoClient(url);
await client.connect()
const dbName = "Chats";
return client.db(dbName);
} catch (e) {
console.log(e)
process.exit(0)
}
}
app.post('/chat/enter', (req, res) => {
let newmsg = new DataClass(req.body.name, req.body.textChat);
add(newmsg).catch(console.dir);
res.render(path.join(__dirname + "/index.ejs"),{texts:texts});
})
async function add(x) {
try{
const db = connectDB();
await db.collection("Users").insertOne({"name":x.name,"textChat":x.msg});
}catch (e) {
console.log(e);
}
}
async function find(){
try{
const db = connectDB();
const a = await db.collection("Users").find({});
console.log(a);
}catch(e){
console.log(e);
}
}
find();
use toArray()
const a= await col.find({}).toArray()

How to mock default package in dependency with Jest?

My dependency includes os and fs with require. I didn't notice any issues with my unit tests until I ran in a Jenkins env which gave this error:
StorageDirectoryResolutionError: Storage directory resolution failedUnsupportedFilePlatform: Platform not supported for file operations
I updated my Jest config to be like this:
moduleNameMapper: {
'^os$': '<rootDir>/tests/dependency-mocks/os.js',
'^fs$': '<rootDir>/tests/dependency-mocks/fs.js',
},
I am mocking os and fs, even though error is around fs, to ensure things are same between my machine and Jenkins.
My os.js is tiny:
module.exports = {
homedir: () => '/user/home',
platform: () => 'darwin',
release: () => 'some release',
};
I have an os.ts file in __mocks__ like this:
export default {
homedir: () => '/user/home',
platform: jest.fn().mockReturnValue('darwin'),
release: jest.fn().mockReturnValue('some release'),
};
My actual file has this issue:
const os = require('os');
console.log(os); // my exported object is on a default key
{ default:
{ homedir: [Function: homedir],
platform:
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockRestore: [Function],
mockReturnValueOnce: [Function],
mockResolvedValueOnce: [Function],
mockRejectedValueOnce: [Function],
mockReturnValue: [Function],
mockResolvedValue: [Function],
mockRejectedValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockName: [Function],
getMockName: [Function] },
release:
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockRestore: [Function],
mockReturnValueOnce: [Function],
mockResolvedValueOnce: [Function],
mockRejectedValueOnce: [Function],
mockReturnValue: [Function],
mockResolvedValue: [Function],
mockRejectedValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockName: [Function],
getMockName: [Function] } } }
This is where it gets very weird. If I do NOT use moduleNameMapper, the dependency does NOT use my mock file. When I do use moduleNameMapper it ignores the .js file for moduleNameMapper and goes to my .ts file in __mocks__. I realized this when I added a random key to the mock and saw the update in console log.
I need the dependency to use os.release() without the object being nested within default.
The answer was really simple. Changed export default {} in mock files to module.exports = {}.
My project uses import/export for nearly everything. Due to the system it runs on, we have to use const fs = require('fs') instead of import fs from 'fs'; The mocks using export had no issue until moduleNameMapper got thrown into the mix.

How can I get the aggregate search value using Mongoose from different Node.js?

I have this mongoose query to get some geoNear value.
const results = await mongoose.connection.db
.collection('placemodels')
.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: [89.9741, 21.5112] },
distanceField: 'calcDistance',
maxDistance: 25000,
spherical: true,
},
},
]);
console.log(results);
However, I am receiving
AggregationCursor {
_readableState: ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
destroyed: false,
errored: false,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
operation: AggregateOperation {
options: { readPreference: [ReadPreference] },
ns: MongoDBNamespace { db: 'test', collection: '$cmd' },
readPreference: ReadPreference { mode: 'primary', tags: undefined },
readConcern: undefined,
writeConcern: WriteConcern { w: 'majority' },
explain: false,
fullResponse: true,
target: 'placemodels',
pipeline: [ [Object] ],
hasWriteStage: false,
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
}
},
pool: null,
server: null,
disconnectHandler: undefined,
bson: BSON {},
ns: 'test.$cmd',
namespace: MongoDBNamespace { db: 'test', collection: '$cmd' },
cmd: {},
options: {
readPreference: ReadPreference { mode: 'primary', tags: undefined }
},
topology: NativeTopology {
_events: [Object: null prototype] {
topologyDescriptionChanged: [Array],
authenticated: [Function (anonymous)],
error: [Array],
timeout: [Array],
close: [Array],
parseError: [Array],
fullsetup: [Array],
all: [Array],
reconnect: [Array],
commandStarted: [Function (anonymous)],
commandSucceeded: [Function (anonymous)],
commandFailed: [Function (anonymous)],
serverOpening: [Function (anonymous)],
serverClosed: [Function (anonymous)],
serverDescriptionChanged: [Function (anonymous)],
serverHeartbeatStarted: [Function (anonymous)],
serverHeartbeatSucceeded: [Function (anonymous)],
serverHeartbeatFailed: [Function (anonymous)],
topologyOpening: [Function (anonymous)],
topologyClosed: [Function (anonymous)],
joined: [Array],
left: [Function (anonymous)],
ping: [Function (anonymous)],
ha: [Function (anonymous)],
connectionPoolCreated: [Function (anonymous)],
connectionPoolClosed: [Function (anonymous)],
connectionCreated: [Function (anonymous)],
connectionReady: [Function (anonymous)],
connectionClosed: [Function (anonymous)],
connectionCheckOutStarted: [Function (anonymous)],
connectionCheckOutFailed: [Function (anonymous)],
connectionCheckedOut: [Function (anonymous)],
connectionCheckedIn: [Function (anonymous)],
connectionPoolCleared: [Function (anonymous)],
open: [Function],
reconnectFailed: [Function (anonymous)]
},
_eventsCount: 36,
_maxListeners: Infinity,
s: {
id: 0,
options: [Object],
seedlist: [Array],
state: 'connected',
description: [TopologyDescription],
serverSelectionTimeoutMS: 30000,
heartbeatFrequencyMS: 10000,
minHeartbeatFrequencyMS: 500,
Cursor: [class Cursor extends CoreCursor],
bson: BSON {},
servers: [Map],
sessionPool: [ServerSessionPool],
sessions: Set(0) {},
promiseLibrary: [Function: Promise],
credentials: [MongoCredentials],
clusterTime: [Object],
connectionTimers: Set(0) {},
srvPoller: [SrvPoller],
detectTopologyDescriptionChange: [Function (anonymous)]
},
[Symbol(kCapture)]: false,
[Symbol(waitQueue)]: Denque { _head: 0, _tail: 0, _capacityMask: 3, _list: [Array] }
},
cursorState: {
cursorId: null,
cmd: {},
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined,
raw: undefined
},
logger: Logger { className: 'Cursor' },
s: {
numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
promiseLibrary: [Function: Promise],
explicitlyIgnoreSession: false
},
[Symbol(kCapture)]: false
}
this result?
I tried to use different queries like .find() and other stuff. Nothing seems to work. How can I get the value from aggregate search? I'd also tried to do query inside of the collection('model', (err, collections) => {---- HERE ----}) and it did not work :(
You need to consume the data from AggregationCursor. One way to do this is:
for (let doc = await results.next(); doc != null; doc = await results.next()) {
console.log(doc);
// process your aggregation result here
}
See the documentation for further details regarding Cursors.

Resources