gpt4 book ai didi

javascript - 如何使用 jest 在 supertest 中模拟模块?

转载 作者:搜寻专家 更新时间:2023-11-01 00:05:13 25 4
gpt4 key购买 nike

伙计们!

我正在使用 Jest 和 Supertest 来测试我的 Node 服务器代码。

这是我的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)
})
})

我在运行测试时在server.js中打印了config,但是打印信息显示jest.mock没有生效(path lib/config 是正确的)。

有人知道在这种情况下使用 Supertest 模拟 config.js 吗??

最佳答案

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

关于javascript - 如何使用 jest 在 supertest 中模拟模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45915261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com