fake response(500) with sinon in post request NodeJs - node.js

can anyone help me out creating a fake response (500) for testing my API using "sinon" , am new to nodeJs , i have tried to test where the return status is 201 and it worked however am still not able to make the fake 500 response
here is my code , thank you in advance
//knex
app.post("/api/categories", function (req, rep) {
knex('categories').insert(req.body)
.then(() => rep.sendStatus(201).json({ message: "Category inserted" }))
.catch((err) => {
console.log(err)
rep.status(500);
})
});
// in my test js
var request=require('supertest');
var KnexApp=require('../KnexFolder/app');
var sinon = require("sinon");
describe("POST/users", ()=>{
describe('when everything is fine and no errors', () => {
it('should respond with status 201',async () => {
const res = await request(KnexApp)
.post('/api/categories')
.send({
name:"from test",
img_id: 5
})
expect(res.statusCode).toEqual(201)
})
})
describe('when There is internal server error', () => {
it('should respond with status 500',async () => {
sinon.stub('/api/categories', "post").throws(
new Error({
response: { status: 500},
})
);
expect(res.statusCode).toEqual(500)
})
})
})

There are two testing strategies:
Stub knex, query interface, and the resolved/rejected value. This way is easier than the second way, you don't need to set up a real testing database and populate testing data.
As mentioned above, you need to set up a real testing database(run your migration script to create database and tables, create the seed testing data, etc...)
I will use the first way to test your code. Since sinon doesn't support stub a function export defaults by a module. We need to use proxyquire package.
app.js:
const express = require('express');
const knex = require('knex')({
client: 'mysql',
connection: {
host: '127.0.0.1',
port: 3306,
user: 'your_database_user',
password: 'your_database_password',
database: 'myapp_test',
},
});
const app = express();
app.use(express.json());
app.post('/api/categories', function (req, rep) {
console.log(req.body);
knex('categories')
.insert(req.body)
.then(() => rep.sendStatus(201).json({ message: 'Category inserted' }))
.catch((err) => {
console.log(err);
rep.sendStatus(500);
});
});
module.exports = app;
app.test.js:
const request = require('supertest');
const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('POST/users', () => {
describe('when everything is fine and no errors', () => {
it('should respond with status 201', async () => {
const queryInterfaceStub = {
insert: sinon.stub().resolves(),
};
const knexStub = sinon.stub().returns(queryInterfaceStub);
const KnexStub = sinon.stub().returns(knexStub);
const KnexApp = proxyquire('./app', {
knex: KnexStub,
});
const res = await request(KnexApp).post('/api/categories').send({
name: 'from test',
img_id: 5,
});
sinon.assert.match(res.statusCode, 201);
});
});
describe('when There is internal server error', () => {
it('should respond with status 500', async () => {
const queryInterfaceStub = {
insert: sinon.stub().rejects(new Error('fake error')),
};
const knexStub = sinon.stub().returns(queryInterfaceStub);
const KnexStub = sinon.stub().returns(knexStub);
const KnexApp = proxyquire('./app', {
knex: KnexStub,
});
const res = await request(KnexApp).post('/api/categories').send({});
sinon.assert.match(res.statusCode, 500);
});
});
});
Test result:
POST/users
when everything is fine and no errors
{ name: 'from test', img_id: 5 }
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:558:11)
at ServerResponse.header (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/response.js:267:15)
at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/71565119/app.js:20:37
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
✓ should respond with status 201 (436ms)
when There is internal server error
{}
Error: fake error
at Context.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/71565119/app.test.js:27:38)
at callFn (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:364:21)
at Test.Runnable.run (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runnable.js:352:5)
at Runner.runTest (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:677:10)
at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:801:12
at next (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:594:14)
at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:604:7
at next (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:486:14)
at Immediate.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/expressjs-research/node_modules/mocha/lib/runner.js:572:5)
at processImmediate (internal/timers.js:461:21)
✓ should respond with status 500
2 passing (448ms)

Related

Jest mock Knex transaction

I have the following lambda handler to unit test. It uses a library #org/aws-connection which has a function mysql.getIamConnection which simply returns a knex connection.
Edit: I have added the mysql.getIamConnection function to the bottom of the post
Edit: If possible, I'd like to do the testing with only Jest. That is unless it becomes to complicated
index.js
const {mysql} = require('#org/aws-connection');
exports.handler = async (event) => {
const connection = await mysql.getIamConnection()
let response = {
statusCode: 200,
body: {
message: 'Successful'
}
}
try {
for(const currentMessage of event.Records){
let records = JSON.parse(currentMessage.body);
await connection.transaction(async (trx) => {
await trx
.table('my_table')
.insert(records)
.then(() =>
console.log(`Records inserted into table ${table}`))
.catch((err) => {
console.log(err)
throw err
})
})
}
} catch (e) {
console.error('There was an error while processing', { errorMessage: e})
response = {
statusCode: 400,
body: e
}
} finally {
connection.destroy()
}
return response
}
I have written some unit tests and I'm able to mock the connection.transaction function but I'm having trouble with the trx.select.insert.then.catch functions. H
Here is my testing file
index.test.js
import { handler } from '../src';
const mocks = require('./mocks');
jest.mock('#org/aws-connection', () => ({
mysql: {
getIamConnection: jest.fn(() => ({
transaction: jest.fn(() => ({
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockReturnThis()
})),
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockReturnThis(),
destroy: jest.fn().mockReturnThis()
}))
}
}))
describe('handler', () => {
test('test handler', async () =>{
const response = await handler(mocks.eventSqs)
expect(response.statusCode).toEqual(200)
});
});
This test works partially but it does not cover the trx portion at all. These lines are uncovered
await trx
.table('my_table')
.insert(records)
.then(() =>
console.log(`Records inserted into table ${table}`))
.catch((err) => {
console.log(err)
throw err
})
How can set up my mock #org/aws-connection so that it covers the trx functions as well?
Edit:
mysql.getIamConnection
async function getIamConnection (secretId, dbname) {
const secret = await getSecret(secretId)
const token = await getToken(secret)
let knex
console.log(`Initialzing a connection to ${secret.proxyendpoint}:${secret.port}/${dbname} as ${secret.username}`)
knex = require('knex')(
{
client: 'mysql2',
connection: {
host: secret.proxyendpoint,
user: secret.username,
database: dbname,
port: secret.port,
ssl: 'Amazon RDS',
authPlugins: {
mysql_clear_password: () => () => Buffer.from(token + '\0')
},
connectionLimit: 1
}
}
)
return knex
}
Solution
#qaismakani's answer worked for me. I wrote it slightly differently but the callback was the key. For anyone interested here is my end solution
const mockTrx = {
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockResolvedValue()
}
jest.mock('#org/aws-connection', () => ({
mysql: {
getIamConnection: jest.fn(() => ({
transaction: jest.fn((callback) => callback(mockTrx)),
destroy: jest.fn().mockReturnThis()
}))
}
}))
Updating your mock to look like this might do the trick:
const { mysql } = require("#org/aws-connection");
jest.mock("#org/aws-connection", () => ({
mySql: {
getIamConnection: jest.fn()
}
}));
const mockTrx = {
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockResolveValue() // Resolve any data here
};
mysql.getIamConnection.mockReturnValue({
transaction: jest.fn((callback) => callback(mockTrx)),
});
You need to mock the transaction so that it executes your callback with a dummy trx. To do this, you need to make sure that all the functions inside the trx object return a reference back to it or a promise so that you can chain it appropriately.
Instead of mocking knex implementation, I've written knex-mock-client which allows you to mimic real db with an easy API.
Change your mock implementation with
import { handler } from "../src";
import { getTracker } from "knex-mock-client";
const mocks = require("./mocks");
jest.mock("#org/aws-connection", () => {
const knex = require("knex");
const { MockClient } = require("knex-mock-client");
return {
mysql: {
getIamConnection: () => knex({ client: MockClient }),
},
};
});
describe("handler", () => {
test("test handler", async () => {
const tracker = getTracker();
tracker.on.insert("my_table").responseOnce([23]); // setup's a mock response when inserting into my_table
const response = await handler(mocks.eventSqs);
expect(response.statusCode).toEqual(200);
});
});

Nestjs e2e test fails with getHttpServer but works with .agent

I was trying to write my first e2e test in nestjs using the following code:
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
AppModule,
]
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
await getConnection().synchronize(true);
});
it('/ (GET)', async () => {
return request(app.getHttpServer())
.get('/')
.expect(200);
});
afterAll(async () => {
await app.close();
});
});
It always fails with 404, when trying to debug the supertest request I saw:
{
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 57523,
response: undefined
}
If I try to connect to the actual app using .agent('127.0.0.1:3000') the test passes.
it('/ (GET)', async () => {
return request
.agent('127.0.0.1:3000')
.get('/')
.expect(200)
});
You have to await the response. Do something like. Look at below snippet where i have added await to response instead of return
it('should throw validation error when creating employer policy', async () => {
const data = {
max_percent_of_salary: true,
is_employer_paid: true,
has_advance_activated: false,
};
const response = await request(app.getHttpServer())
.post('/sa-employer-policy/create/')
.set('Accept', 'application/json')
.set('Authorization', 'Bearer ' + employer_token)
.send(data)
.expect(HttpStatus.BAD_REQUEST);
expect(response.body.message).toBeDefined();
});
The problem was that I was using an endpoint from a controller without importing the parent module.

Fetch API failed to Fetch during authentication, alongside CORS error

I have a button that lauches a fetch to my API that uses KOA and JWT. The javascript for the fetch initiated on click is:
<script>
function loginButton(user, pass) {
fetch('http://localhost:5454/api/login', {
method: "post",
headers: {
'Content-Type': "application/json"
},
body: JSON.stringify({
username: user,
password: pass
})
})
.then( (response) => {
console.log("Success")
})
.catch(e => console.log(e));
}
</script>
The code for my Authentication is:
router.post(`${BASE_URL}/login`, async (ctx) => {
const reqUsername = ctx.request.body.username
const reqPassword = ctx.request.body.password
const unauthorized = (ctx) => {
ctx.status = 401
ctx.body = {
error: 'Invalid username or password'
}
}
let attemptingUser
try {
attemptingUser = await Employee.findOne({ where: { username: reqUsername }})
if (attemptingUser != null && attemptingUser.password === reqPassword) {
ctx.status = 200
ctx.body = {
username: attemptingUser.username,
given_name: attemptingUser.given_name,
role: attemptingUser.role,
created_at: attemptingUser.createdAt,
updated_at: attemptingUser.updatedAt,
}
const token = jwt.sign({ username: attemptingUser.username, role: attemptingUser.role }, SECRET)
ctx.set("X-Auth", token)
} else {
unauthorized(ctx)
}
} catch(err) {
console.error(err)
console.error(`Failed to find username: ${reqUsername}`)
unauthorized(ctx)
}
})
The code for my KOA initiation is:
require('dotenv').config()
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const baseRoutes = require('./routes')
const cors = require('#koa/cors');
const PORT = process.env.PORT || 8080
const app = new Koa()
app.use(bodyParser())
app.use(baseRoutes.routes())
app.use(cors());
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`)
})
Im using Port 8080 for my http-server and port 5454 for my npm server. I am getting a Failed to Fetch in the catch of the Fetch, as well as a CORS error related to not having a Access-Control-Allow-Origin header in the response header. I've tried a couple things and am ready to have a new set of eyes look at it, any tips?
Edit: I am successfully receiving the token in the X-Auth header, but for some reason it’s still throwing errors and I’d like to get them resolved before it spirals out of control.

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