如何通过使用笑话嘲笑超级模块?

伙计们!

我正在使用Jest和Supertest来testing我的节点服务器代码。

这是我的server.js

 // server.js const config = require('./lib/config') ... const app = new koa() ... module.exports = app 

我想在使用Supertest的时候模拟config.js ,这里是我的server.test.js

 // server.test.js const supertest = require('supertest-as-promised') describe('xxxxxx', ()=>{ let app,server beforeEach(()=>{ jest.mock('lib/config',()=>({ uri: '/path', apiPrefix: '/prefix' })) app = require('server') }) afterEach(()=>{ server && server.close() app=null server=null }) it('should success', async ()=>{ server || (server = app.listen(0)) const request = supertest(server) request().get('path/prefix_home').expect(200) }) }) 

我在运行testing时在server.js打印了config ,但打印信息显示jest.mock不起作用( lib/configpath正确)。

任何人有任何想法嘲笑config.js在这种情况下使用Supertest?

Jest似乎解决了path,所以你在./lib/config时提供的path必须是一致的:如果server.test.js位于server.js旁边,它应该是./lib/config 。 如果文件位于不同的位置,则需要相应地构buildpath,例如../src/lib/config如果server.js位于src文件夹中,并且server.test.js位于src旁边的test文件夹中