Tengo un complemento de Twitter que usa axios internamente para llamar a la API oembed de Twitter. En las pruebas unitarias, me gustaría bloquear/simular estas llamadas externas con sinon. Sin embargo, por alguna razón, la llamada sinon.stub() no reemplaza la implementación de axios.get dentro de la implementación concreta en twitter.js
twitter.spec.js:
const axios = require('axios') const tweetIncludePlugin = require('../../../../../plugins/includes/twitter') const tweetFunction = tweetIncludePlugin() this.renderFn = tweetFunction.rendering.render describe('Twitter Plugin:', function () { let stub beforeEach(async function () { stub = sinon.stub(axios, 'get').resolves({data: {html: 'OEMBED_RETURNED_HTML'}}) } it('with existing tweet embedLink', async function () { const includeParams = {embedLink: 'https://twitter.com/dsdsd/status/xy'} const {html} = await this.renderFn(includeParams, {}) sinon.assert.calledOnce(stub) expect(html).to.be.a('string').and.equals('OEMBED_RETURNED_HTML') }) }tuit.js:
const axios = require('axios') module.exports = function () { async function renderTweet (params, options) { const embedLink = _.get(params, 'embedLink') const url = `http://publish.twitter.com/oembed?url=${embedLink};dnt=true;maxheight=300;maxwidth=400;` await axios.get(url) .then(response => { console.log(`Success ${response.status}, data: ${response.data.html}`) const html = response.data.html return html }) } return { name: 'twitterPlugin', rendering: { type: 'function', render (params, options) { return renderTweet(params, options) } } } }Después de algunas pruebas y errores, descubrí que si coloco
const tweetIncludePlugin = require('../../../../../plugins/includes/twitter') const tweetFunction = tweetIncludePlugin() this.renderFn = tweetFunction.rendering.render después de la stub = sinon.stub(axios, 'get').resolves({data: {html: 'OEMBED_RETURNED_HTML'}}) , ¡funciona! ¡Pero no entiendo por qué! Según tengo entendido, ambas llamadas require() adquirirán una referencia a la misma instancia de módulo de axios en la que .get() debería haberse burlado, ¿no?