I have an express app like this:
server.js
const postsController = require('./controllers/posts_controller.js')
module.exports = app = express()
app.get('posts', postsController.index)
posts_controller.js
const thirdPartyApi = require('third_party_api')
module.exports = {
index: (req, res) => {
thirdPartyApi.get().then((posts) => {
res.status(200).send(posts)
}, (error) => {
res.status(400).send('text')
})
}
}
spec/posts_controller_spec.js
const app = require('../server')
const request = require('supertest')
describe('GET /posts', () => {
it('should retu a collection of posts', () => {
request(app)
.get('/posts')
.end((_err, resp) => {
expect(resp.status).toEqual(200)
})
})
})
My goal here is to stub out the thirdPartyApi.get(). I tried with proxyquire by adding this line to posts_controller_spec:
proxyquire('../posts_controller', {third_party_api: {
get: () => { console.log('stubbed out get method'); }
})
This doesn't work because the server.js file is the file that requires the third_party_api again.
I could do something like this to test the controller:
const postsController = proxyquire('../posts_controller', {third_party_api: {
get: () => { console.log('stubbed out get method'); }
})
postsController.index(req, res)
This second strategy doesn't feel right because now I have to stub req and res and now I'm bypassing the actual app instance.
Is there an easy way to do this, with proxyquire, or otherwise?
