Alright, so I have a very simple API that basically returns information on currencies. I am trying to use the clean code approach and I am having a hard time making this test work. Here is what I got so far (I used ** wrapping the main statements):
This is controllers/getCurrency.js
const makeGetCurrency = ({ errorMessages, retrieveCurrency }) => {
return async function getCurrency(httpRequest, myCache) {
try {
const {
from,
to,
amount
} = httpRequest.query
const { ip, headers, source = {} } = httpRequest
source.ip = ip
source.browser = headers["User-Agent"]
if (headers["Referer"]) {
source.referer = headers["Referer"]
}
**const currencyConversion = await retrieveCurrency({ from, to, amount, myCache })**
return {
statusCode: 200,
body: currencyConversion
}
}
catch (err) {
const { status, body } = errorMessages[err.message] || { status: 400, body: err.message }
return {
headers: {
"Content-Type": "application/json",
},
statusCode: status,
body: {
error: body,
}
}
}
}
}
That is the controller I am trying to test. What I need to mock is this return:
const currencyConversion = await retrieveCurrency
This function is being passed by another parent file called:
controllers/index.js
const makeGetHealth = require('./health')
const makeGetCurrency = require('./currency/getCurrency')
const errorMessages = require('../error-messages.json')
//use-cases
**const { retrieveCurrency } = require('../_use-cases')**
const getHealth = makeGetHealth()
const getCurrency = makeGetCurrency({ errorMessages, retrieveCurrency })
module.exports = {
getHealth,
getCurrency,
}
Since retrieveCurrency
is actually exported on use-cases/index.js
I am trying to test the API like below:
const useCases = require('../../src/_use-cases')
describe("GET /currency ", () => {
let sandbox
beforeEach(() => {
sandbox = sinon.createSandbox()
})
//test a function for a specific case
it("returns status 200 ", async () => {
**const retrieveCurrencyStub = sandbox.stub(useCases, 'retrieveCurrency').resolves({
test: 'test'
})**
const { statusCode, body } = await chai.request(createServer()).get('/conversion?from=USD&to=BRL&amount=10')
console.log(body) //not returning my stub's response
expect(statusCode).to.equal(200)
expect(retrieveCurrencyStub).to.be.called //is never called
})
That is how my routes are setup
const setUpRoutes = (myCache) => {
app.get('/health', expressCallBack(getHealth, myCache))
app.get('/conversion', expressCallBack(getConversion, myCache))
app.post('/currency', expressCallBack(postCurrency, myCache))
app.delete('/currency', expressCallBack(deleteCurrency, myCache))
return app
}
Does anyone know how to make this work?
Thank you so much