I have this file which sends otp like below.
OtpService.js
const generateOTP = async function() {
//
}
const verifyOTP = async function() {
//
}
module.exports = {
generateOTP,
verifyOTP
}
Below is the controller that uses these methods, otp.js
const { verifyOTP, generateOTP } = require('../../services/OtpService')
const verify = async function(req, res) {
const {error, data} = await generateOTP(req.query.phone)
}
const send = async function(req, res) {
const {error, data} = await verifyOTP(req.query.phone, req.query.otp)
}
module.exports = {
send,
verify
}
below is the test file otp.test.js
const sinon = require('sinon');
const expect = require('chai').expect
const request = require('supertest')
const OtpService = require('../../src/services/OtpService')
console.log(OtpService)
describe('GET /api/v1/auth/otp', function() {
let server
let stub
const app = require('../../src/app')
stub = sinon.stub(OtpService, 'generateOTP').resolves({
error: null,
data: "OTP Sent"
})
server = request(app)
it('should generate OTP', async () => {
const result = await server
.get('/api/v1/auth/otp/send?phone=7845897889')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
console.log(result.body)
expect(stub.called).to.be.true
expect(result).to.be.a('Object')
});
});
Above is not working, it's not stubbing the generateOTP and verifyOTP methods when called in the controller.
However, If I call OtpService.generateOTP() in the otp.test.js then it is working there, but it doesn't work in the controller.
Hhow sinon is working here?
I am confused here. Does requiring the app and then stubbing is correct or stubbing first and then requiring is correct?
I have tried both ways though neither of them work.
I also tried using before() and beforeEach().
Below is my folder structure.
otp.js(controller) is here controller->AuthController->otp.js
otp.test.js is here test->auth->otp.test.js
OtpService.js is just inside services
Update
I found the the problem.
If I don't use destructing feature in the controller everything works fine. So, using OtpService.generateOTP works.
Problem is with the destructing of the objects.
const { verifyOTP, generateOTP } = require('../../services/OtpService')
Above is being run before the stubbing. So verifyOTP and generateOTP already has a reference to the unstubbed methods.
I need a workaround here. I want to use destructing feature.
