Setting Bearer Token in the header section while testing with Supertest - node.js

I'm trying to add the Bearer in the header section in POST request while testing with Supertest. I tried many methods. I'm a beginner in testing. Please suggest some better ways to achieve this.
here is my sample code. What is wrong with this?
it('POST/userAuth', async (done) => {
const res = await request
.post('/v1/user/haha')
.set('Authorization', `bearer ${Token}`)
.send({
title: 'Some random text',
options: [
{ start: hello, end: world },
{ start: good, end: bye },
],
});

You can set a request header like this:
const request = require('supertest');
const express = require('express');
const app = express();
const TOKEN = 'some_token';
describe('POST /some-url', function() {
it('does something', function(done) {
request(app)
.post('/some-url')
.send({ body: 'some-body' })
.set('Authorization', `Bearer ${TOKEN}`)
.expect(200, done);
});
});

in superagent docs you can find specialized .auth method
interface Request extends Promise<Response> {
auth(user: string, pass: string, options?: { type: "basic" | "auto" }): this;
auth(token: string, options: { type: "bearer" }): this;
...
}
(supertest is using superagent under the hood)
I prefer to set auth in before function for all tests in the set.
import * as Koa from 'koa';
import * as http from 'http';
import { agent as superagent } from 'supertest';
import { UserController } from './user-controller';
const testBearerToken = 'test-bearer-token';
describe('user controller', async () => {
context('simple user', async () => {
it('should save user', async () => {
const response = await test
.post('/v1/user/haha')
// you can here, but rather set it in the before function
//.auth(testBearerToken, { type: 'bearer' });
.send({
title: 'Some random text',
options: [
{ start: 'hello', end: 'world' },
{ start: 'good', end: 'bye' },
],
});
// .expect(...)
// expect(response)...
});
});
let test;
before(async () => {
const app = new Koa();
const userController = new UserController();
app.use(userController.middleware());
test = superagent(http.createServer(app.callback()))
.auth(testBearerToken, { type: 'bearer' });
});
});

Related

.send() send an empty body mocha node js

I have an issue with the following code. The mocha .send() function send a body but it's empty when my api.js received it. When I do a request with PostMan it works, but when I use Mocha, it doesn't work.
api.js :
const express = require("express");
const dbConnection = require("../db/mysqlConnector.js");
const router = express();
const Validator = require('validatorjs');
// POST (Create)
router.post("/tasks", async function (req, res) {
try {
let validation = new Validator({
name: req.body.name,
description: req.body.description,
state: req.body.state,
priority: req.body.priority,
created_by: req.body.created_by
}, {
name: 'required|string',
description: 'required|string',
state: 'required|boolean',
priority: 'required|between:1,3',
created_by: 'required:number'
});
if (validation.fails()) { return res.status(400).json(); }
var con = await dbConnection();
await con.query('INSERT INTO `tasks` (name, description, state, priority, created_by) VALUES (?,?,?,?,?)',
[req.body.name, req.body.description, req.body.state, req.body.priority, req.body.created_by], function (error, results, fields) {
con.release();
res.status(201).json();
});
} catch (error) {
console.log(error);
}
});
test.js :
const chai = require("chai");
const request = require("supertest");
const expect = chai.expect;
const api = require("../routes/api.js");
const faker = require("faker");
describe("Tasks", function () {
describe("POST /tasks", function () {
it("should return 201 OK and insert a new task", async function () {
const response = await request(api)
.post("/tasks")
.send({
name: faker.vehicle.vehicle(),
description: faker.lorem.lines(3),
state: faker.datatype.boolean(),
priority: faker.datatype.number({min:1, max:3}),
created_by: faker.datatype.number({min:1, max:10})
})
.expect(201)
});
});
});
Am I missing something ?
Thanks

Learn about apollo-graphql Subscription

I'm presently studying Graphql(apollo) and utilising Node.js for the backend.
I've made some progress with queries and mutations, but I'm stuck at subscription. I've seen several videos and read some blogs, but I'm having trouble grasping it since they're utilising front-end frameworks, such as react, and I'm not familiar with react or any other front-end javascript frameworks.
I'm solely interested in learning it for the backend.
Is there anyone who can assist me with this?
I've got three separate queries (or whatever they're called) that I'm working on.
User,
Post and
Comment
Now I want to generate a subscription whenever someone adds a new comment or creates a new post.
For users, comments, and posts, I already have a mutation for add, update and remove.
There is currently no authentication or authorization in place.
Your question is more to help me implement this rather than actually asking an issue or problem you faced after trying out some steps in series of order.
This might help you when learning and implementing GraphQL subscription;
https://www.apollographql.com/docs/apollo-server/data/subscriptions/
https://www.youtube.com/watch?v=R2IrBI4-7Kg&t=698s
If you have tried something and faced a wall, please add your code and what you have done, so I could help you on where you are wrong or what you could do hopefully. Cheers.
The solutions I'm providing are crafted on #apollo/server v.4, with expressMiddleware and mongodb/mongoose on the backend and subscribeToMore with updateQuery on the client-side instead of the useSubscription hook.
The graphql-transport-ws transport library is no longer supported; instead, use graphql-ws.
The implementation differentiates three main collections: User, Post, and Comment, as well as subscription for post creation, post modification, and user authentication.
Likewise, as of 12.2022, the following setup and configuration apply.
Subscription on the backend:
Install the following dependencies:
$ npm i #apollo/server #graphql-tools/schema graphql-subscriptions graphql-ws ws cors body-parser mongoose graphql express
I'm assuming you've already configured your MongoDB models; if not, you might want to look at this repo for a basic setup.
Set up schema types and resolvers, such as this one.
// typeDefs.js
const typeDefs = `#graphql
type User {
id: ID!
email: String!
posts: [Post]!
commentsMade: [Comment]!
}
type Token {
value: String!
}
input UpdatePostInput {
title: String!
}
type Post {
id: ID!
title: String!
postedBy: User
comments: [Comment]!
}
input CommentInput {
text: String!
}
type Comment {
id: ID!
text: String!
commenter: User!
commentFor: Post!
}
type Query {
users: [User]!
user(id: ID!): User!
posts: [Post!]!
post(id: ID!): Post!
comment(id: ID!): Comment!
comments: [Comment!]!
}
type Mutation {
signup(email: String!, password: String!): User
signin(email: String!, password: String!): Token
createPost(title: String): Post
createComment(postId: String!, commentInput: CommentInput!): Comment
updatePost(postId: ID!, updatePostInput: UpdatePostInput!): Post
}
type Subscription {
postAdded: Post
commentAdded: Comment
postUpdated: Post
}
`
export default typeDefs
// resolvers.js
import dotenv from 'dotenv'
import { PubSub } from 'graphql-subscriptions'
import mongoose from 'mongoose'
import { GraphQLError } from 'graphql'
import bcrypt from 'bcrypt'
import UserModel from '../models/User.js'
import PostModel from '../models/Post.js'
import CommentModel from '../models/Comment.js'
dotenv.config()
...
const pubsub = new PubSub()
const User = UserModel
const Post = PostModel
const Comment = CommentModel
const secret = process.env.TOKEN_SECRET
const resolvers = {
Query: {...},
Mutation: {
...
createPost: async (_, args, contextValue) => {
const authUser = contextValue.authUser
if (!authUser) {
throw new GraphQLError('User is not authenticated', {
extensions: {
code: 'UNAUTHENTICATED',
http: { status: 401 },
},
})
}
const post = new Post({
...args,
postedBy: mongoose.Types.ObjectId(authUser.id),
})
try {
const savedPost = await post.save()
authUser.posts = authUser.posts.concat(post._id)
await authUser.save()
const addedPost = {
id: savedPost.id,
title: savedPost.title,
postedBy: savedPost.postedBy,
comments: savedPost.comments,
}
// subscription postAdded with object iterator POST_ADDED
pubsub.publish('POST_ADDED', { postAdded: addedPost })
return post
} catch (error) {
throw new GraphQLError(`Error: ${error.message}`, {
extensions: {
code: 'BAD_USER_INPUT',
http: { status: 400 },
argumentName: args,
},
})
}
},
updatePost: async (_, args, contextValue) => {
const authUser = contextValue.authUser
if (!authUser) {
throw new GraphQLError('User is not authenticated', {
extensions: {
code: 'UNAUTHENTICATED',
http: { status: 401 },
},
})
}
try {
const post = await Post.findByIdAndUpdate(
args.postId,
args.updatePostInput,
{ new: true }
)
.populate('comments')
.populate('postedBy')
const updatedPost = {
id: post.id,
title: post.title,
postedBy: post.postedBy,
comments: post.comments,
}
// subscription postUpdated with object iterator POST_UPDATED
pubsub.publish('POST_UPDATED', { postUpdated: updatedPost })
return post
} catch (error) {
throw new GraphQLError(`Error: ${error.message}`, {
extensions: {
code: 'BAD_REQUEST',
http: { status: 400 },
argumentName: args,
},
})
}
},
},
// resolvers for post addition and post modification using subscribe function
Subscription: {
postAdded: {
subscribe: () => pubsub.asyncIterator('POST_ADDED'),
},
commentAdded: {
subscribe: () => pubsub.asyncIterator('COMMENT_ADDED'),
},
postUpdated: {
subscribe: () => pubsub.asyncIterator('POST_UPDATED'),
},
},
//Hard-coding the default resolvers is appropriate in some cases,
// but I think it is required in fields with references to other
//database models to avoid returning null field values.
Post: {
id: async (parent, args, contextValue, info) => {
return parent.id
},
title: async (parent) => {
return parent.title
},
postedBy: async (parent) => {
const user = await User.findById(parent.postedBy)
.populate('posts', { id: 1, title: 1, comments: 1, postedBy: 1 })
.populate('commentsMade')
//console.log('id', user.id)
//console.log('email', user.email)
return user
},
comments: async (parent) => {
return parent.comments
},
},
Comment: {
id: async (parent, args, contextValue, info) => {
return parent.id
},
text: async (parent, args, contextValue, info) => {
return parent.text
},
commenter: async (parent, args, contextValue, info) => {
const user = await User.findById(parent.commenter)
.populate('posts')
.populate('commentsMade')
return user
},
commentFor: async (parent, args, contextValue, info) => {
const post = await Post.findById(parent.commentFor)
.populate('comments')
.populate('postedBy')
return post
},
},
...
}
export default resolvers
The code in the main entry server file (e.g. index.js) may look like this, e.g.
import dotenv from 'dotenv'
import { ApolloServer } from '#apollo/server'
import { expressMiddleware } from '#apollo/server/express4'
import { ApolloServerPluginDrainHttpServer } from '#apollo/server/plugin/drainHttpServer'
import { makeExecutableSchema } from '#graphql-tools/schema'
import { WebSocketServer } from 'ws'
import { useServer } from 'graphql-ws/lib/use/ws'
import express from 'express'
import http from 'http'
import cors from 'cors'
import bodyParser from 'body-parser'
import jwt from 'jsonwebtoken'
import UserModel from './models/User.js'
import typeDefs from './tpeDefs.js'
import resolvers from './resolvers.js'
import mongoose from 'mongoose'
dotenv.config()
mongoose.set('strictQuery', false)
let db_uri
if (process.env.NODE_ENV === 'development') {
db_uri = process.env.MONGO_DEV
}
mongoose.connect(db_uri).then(
() => {
console.log('Database connected')
},
(err) => {
console.log(err)
}
)
const startGraphQLServer = async () => {
const app = express()
const httpServer = http.createServer(app)
const schema = makeExecutableSchema({ typeDefs, resolvers })
const wsServer = new WebSocketServer({
server: httpServer,
path: '/',
})
const serverCleanup = useServer({ schema }, wsServer)
const server = new ApolloServer({
schema,
context: async ({ req }) => {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token) {
const decoded = jwt.verify(token, process.env.TOKEN_SECRET)
const authUser = await UserModel.findById(decoded.id)
.populate('commentsMade')
.populate('posts')
return { authUser }
}
},
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose()
},
}
},
},
],
})
await server.start()
app.use(
'/',
cors(),
bodyParser.json(),
expressMiddleware(server, {
context: async ({ req }) => {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token) {
const decoded = jwt.verify(token, process.env.TOKEN_SECRET)
const authUser = await UserModel.findById(decoded.id)
.populate('commentsMade')
.populate('posts')
return { authUser }
}
},
})
)
const PORT = 4000
httpServer.listen(PORT, () =>
console.log(`Server is now running on http://localhost:${PORT}`)
)
}
startGraphQLServer()
END. It's time to run some tests and checks in the Apollo Explorer sandbox. Be conscientious about defining the required default resolvers to avert the Apollo server from sending null values on your behalf.
To view the code and implementation, go to this repository.
Happy coding!

Node, Sinon, Mocha mock default exported function

I'm trying to mock the import nodeVault so that I can set the return value for the read function.
I have the following code:
import nodeVault from 'node-vault';
const getVaultClient = (vaultToken) => {
return nodeVault({
apiVersion: 'v1',
endpoint: process.env.VAULT_URL,
token: vaultToken.auth.client_token,
});
}
const getCredentialsFromVault = async () => {
const vaultToken = await getVaultToken();
const vault = getVaultClient(vaultToken);
const { data } = await vault.read(process.env.VAULT_SECRET_PATH);
return { client_id: data.client_id, client_secret: data.client_secret, grant_type: 'client_credentials' };
};
I then have a unit test:
describe('AttributeLoad', () => {
let sandbox;
let pedApiMock;
let authApiMock;
let vaultAuthenticateMock;
let nodeVaultClientMock;
beforeEach(() => {
sandbox = createSandbox();
process.env = { VAULT_URL: 'testVault', VAULT_SECRET_PATH: 'testPath' };
pedApiMock = sandbox.stub(attributeLoader.pedApi, 'post');
authApiMock = sandbox.stub(attributeLoader.authApi, 'post');
vaultAuthenticateMock = sandbox.stub(vaultAuthAws.prototype, 'authenticate');
nodeVaultClientMock = sandbox.stub(nodeVault.prototype, ''); --------> Not sure what should go here
I have tried read and constructor
});
afterEach(() => {
sandbox.restore();
});
it('Should call api with correct request body and correctly filter successes and rejections', async () => {
const expectedOutput = {
rejectedLines: [
....
],
validLines: [
.....
]
};
const mockAuthResponse = {
data: {
access_token: 'mocktoken',
},
};
const mockVaultToken = {
auth: {
client_token: ''
}
};
const expectedAuthParams = {
client_id: '',
client_secret: '',
grant_type: 'client_credentials',
};
const mockVaultData = {
data: {
client_id: '',
client_secret: '',
}
};
pedApiMock.returns(Promise.resolve(mockResponse));
authApiMock.returns(Promise.resolve(mockAuthResponse));
vaultAuthenticateMock.returns(Promise.resolve(mockVaultToken));
nodeVaultClientMock.returns(Promise.resolve(mockVaultData));
const finalTestData = await attributeLoader.load(testInputData);
assert.calledWith(authApiMock, expectedAuthParams);
expect(finalTestData.rejectedLines).to.deep.equal(expectedOutput.rejectedLines);
expect(finalTestData.validLines).to.deep.equal(expectedOutput.validLines);
});
});
Everything I try gives this error:
"before each" hook for "Should call api with correct request body and correctly filter successes and rejections":
TypeError: Cannot stub non-existent property read* ---> or any function I try to mock
I've also tried to spy on nodeVault.
Any and all help would be greatly appreciated
So after some more digging I was able to mock node vault by using proxyquire:
import proxyquire from 'proxyquire';
const attributeLoader = proxyquire('../src/attributeLoader', { 'node-vault': () => { return { read: () => mockVaultData } } });
and that fixed it.

Mock an external endpoint in NodeJs by Moxios

I am trying to mock an external endpoint of Twilio in the unit test by Moxios library. I am also using SuperTest library to provide the exceptions of the test.
My internal endpoint which is called by Front-end is:
router.get('/twilio', async (req, res, next) => {
const result = await validatePhoneNumber(68848239, 'SG');
res.status(200).json(result);
});
and validatePhoneNumber is a function which calls the external endpoint by Axios which I am trying to mock and not to call the actual endpoint during the test:
const validatePhoneNumber = async (phone, code) => {
const endpoint = `https://lookups.twilio.com/v1/PhoneNumbers/${phone}?CountryCode=${code}`;
try {
const { status } = await axios.get(endpoint, {
auth: {
'username': accountSid,
'password': authToken
}
});
console.log('twilio', phone, status);
return {
isValid: status === 200,
input: phone
};
} catch (error) {
const { response: { status } } = error;
if (status === 404) {
// The phone number does not exist or is invalid.
return {
input: phone,
isValid: false
};
} else {
// The service did not respond corrctly.
return {
input: phone,
isValid: true,
concerns: 'Not validated by twilio'
};
}
}
};
And my the unit test code:
const assert = require('assert');
const request = require('supertest');
const app = require('../app');
const axios = require('axios');
const moxios = require('moxios');
describe('some-thing', () => {
beforeEach(function () {
moxios.install()
})
afterEach(function () {
moxios.uninstall()
})
it('stub response for any matching request URL', async (done) => {
// Match against an exact URL value
moxios.stubRequest(/https:\/\/lookup.twilio.*/, {
status: 200,
responseText: { "isValid": true, "input": 68848239 }
});
request(app)
.get('/twilio')
.expect(200, { "isValid": true, "input": 68848239 }, done);
});
});
If in my case Moxios is the right way to mock any external endpoints, I am getting the error below:
Error: Timeout of 3000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (c:\Source\Samples\Twilio\myproject\test\twilio.test.js)
I increased the time out to 10000 but still I get a same error.
Appreciate any hint or help.
I tried different ways but I prefer to go on with axios-mock-adapter library to mock any request through Axios.
Example:
const app = require('../app');
const axios = require('axios');
const request = require('supertest');
const MockAdapter = require('axios-mock-adapter');
describe('Valid phone number', () => {
it('Should return data from response', (done) => {
let mockAdapter = new MockAdapter(axios);
mockAdapter.onGet(twilioEndpoint)
.reply(200);
request(app)
.post('/api/validation')
.set('Content-Type', 'application/json')
.send(JSON.stringify(configuration))
.expect(200, { "isValid": true, "input": "68848239" }, done);
});
});
More information here

when trying to test my hapijs application "register" [1]: -- missing --

I am using hapijs v17.2.3 . Also I am very new to hapi .I am trying to test my code using Lab a simple test utility for Node.js and code assertion library.
my test.js file is :
'use strict';
var path = require('path');
var dotEnvPath = path.resolve('./.env');
require('dotenv').config({ path: dotEnvPath });
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;
const Joi = require('joi');
const Hapi = require('hapi');
const app = require('../app');
const server = new Hapi.Server();
const getServer = async () => {
const server = new Hapi.Server();
// server.connection();
return server.register(app)
.then(() => server);
};
lab.experiment('signup testing in "/signup"', () => {
lab.test('Return true if the user can successfully signup', (done, flags) => {
const signUpData = {
method: 'POST',
url: '/signup',
payload: {
name: 'vulcan',
password: 'vulcan#123',
email: 'vulcan#gmail.com',
username: 'vulcan123',
dob: '12-08-1994'
}
};
getServer()
.then((server) => server.inject(signUpData))
.then((response) => {
flags.note(`demo test note`);
if (response) {
console.log(response.statusCode);
Code.expect(response.statusCode).to.equal(201);
Code.expect(payload).to.contain(['name', 'password', 'email', 'username', 'dob']);
}
done();
});
});
});
lab.experiment('1) login test ', () => {
lab.test('login has successfully done', (done) => {
const loginData = {
method: 'POST',
url: '/login',
payload: {
email: 'wrong email',
login_password: 'wrong password',
}
};
getServer()
.then((server) => {
server.inject(loginData)
})
.then((response) => {
Code.expect(response.statusCode).to.equal(200);
done();
});
});
});
my test command is : lab --assert code --coverage -t 100
my signup controller is :
exports.postForm = {
description: 'Submit the signup page',
tags: ['api'],
notes: 'accepts name password verify and email',
auth: {
mode: 'try',
strategy: 'session'
},
validate: {
payload: {
name: Joi.string().required(),
password: Joi.string().min(4).max(20).required(),
verify: Joi.string().required(),
email: Joi.string().email().required(),
username: Joi.string().min(3).max(20).required(),
referredBy: Joi.any(),
dob: Joi.date().required().label('Date of Birth')
},
failAction: (request, h, error) => {
console.log('Validation Failed');
request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
return h.redirect('/signup').takeover();
}
},
handler: async (request, h) => {
try {
var user = {
name: request.payload.name,
password: request.payload.password,
email: request.payload.email,
username: request.payload.username.toLowerCase(),
referralName: request.payload.username + '#gg',
emailConfirmationToken: uuidv1(),
dob: request.payload.dob,
tnc: true
};
let data = await signupHelper.signUpUser(user, request);
if (data.statusCode === 201) {
if (request.payload.referredBy) {
let configureReferral = await signupHelper.configureReferral(request.payload.referredBy, data.userId);
if (configureReferral.statusCode === 200) {
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
}
}
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
} else {
request.yar.flash('error', data.message);
return h.redirect('/signup');
}
} catch (error) {
logger.error(error);
return h.redirect('/signup');
}
}
};
my login control :
exports.login = {
description: 'Post to the login page',
notes: 'Accepts two paramters email and password which got validation',
tags: ['api'],
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
crumb: {
key: 'crumb',
source: 'payload',
},
'hapi-auth-cookie': {
redirectTo: false
}
},
validate: {
payload: {
email: Joi.string().min(3).email().required(),
login_password: Joi.string().min(4).required()
},
failAction: (request, h, error) => {
request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
return h.redirect('/login').takeover();
}
},
handler: async (request, h) => {
try {
const next = request.query.next ? request.query.next : '/dashboard';
if (request.auth.isAuthenticated) {
return h.redirect(next);
}
let resultData = await loginHelper.findByCredentials(request.payload.email, request.payload.login_password);
if (resultData.statusCode === 200) {
request.cookieAuth.set(resultData.user);
return h.redirect(next);
} else {
request.yar.flash('error', resultData.message);
return h.redirect('/login');
}
} catch (error) {
logger.error(error);
request.yar.flash('error', error.message);
return h.redirect('/login');
}
}
};
this is the error when I run the test:
Socket server start initiated
Socket server started
Server started at https://127.0.0.1:8000
signup testing in "/signup"
✔ 1) Return true if the user can successfully signup (3615 ms)
1) login test
✖ 2) login has successfully done
(node:9708) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Invalid plugin options {
"plugin": {
"sock": {
"init": function (server, options) {\n
..........
..........
},
"register" [1]: -- missing --
}
}
[1] "register" is required
at new AssertionError (internal/errors.js:102:11)
at Object.exports.assert (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/node_modules/hoek/lib/index.js:517:11)
at Object.exports.apply (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/config.js:22:10)
at internals.Server.register (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/server.js:410:31)
at getServer (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:23:19)
at lab.test (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:115:9)
at Immediate.setImmediate [as _onImmediate] (/home/jeslin/projects/hapi/gamergully/node_modules/lab/lib/runner.js:628:31)
at runCallback (timers.js:810:20)
at tryOnImmediate (timers.js:768:5)
at processImmediate [as _immediateCallback] (timers.js:745:5)
(node:8764) 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(). (rejection id: 6)
(node:8764) [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.
Mongo Database connected
when I run only one test case, it wont return any error. If I run more
than one this error is showing
I have done this by following this link
This could be related to your server instance creation. In one test you are trying to create more than one server instance with the same configuration. That might be the problem I think. When I create tests, I am using lab.before and lab.beforeEach methods to create instances.
Here is a real-world test case from one of my projects.
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const before = lab.before;
const after = lab.after;
const expect = require('code').expect;
// ..... other stufff
describe('Test Routes', () => {
let server;
before(async () => {
server = new Hapi.Server();
await server.register(app)
});
after(async () => {
await server.stop();
});
it('It should obtain valid response', async () => {
const qs = querystring.stringify(queryParams);
const res = await server.inject({
url: `/s?${qs}`,
method: 'get',
headers: {
"Cookie": "user=aighaeshaighaPopaGoochee8ahlei8x"
}
});
expect(res.statusCode).to.equal(200);
expect(res.result.userid).to.exist();
expect(res.result.status).to.equal(true);
// handle play action
const res2 = await server.inject({
url: `/b?id=${res.result.userid}`,
method: 'get'
});
expect(res2.statusCode).to.equal(200);
expect(res2.result.status).to.equal(true);
});
//
it('It should reject invalid request', async () => {
const res = await server.inject({
url: `/a?a=b&id=iChah3Ahgaaj2eiHieVeem6uw2xaiD5g`,
method: 'get'
});
expect(res.statusCode).to.equal(200);
expect(res.result.status).to.equal(false);
expect(res.result.message).to.equal("Invalid information");
});
// ... goes on
});
Just pay attention to before and after calls. I am creating only one instance of server then using it along side my test cases or use beforeEach and afterEach to isolate your instances, it's your choice.

Resources