我刚刚开始使用Pactum对API端点进行单元测试。
在我的一个API端点中,我调用了一个外部API,并尝试模拟这个外部API。我的代码显然调用了外部API。
但是,我的测试失败了,我得到了一个错误(实际端点32只是一个示例,它不是在实际代码中硬编码的):Interaction not exercised: GET - https://62b32eab4f851f87f4563d9b.mockapi.io/user/32
下面是我测试的一个样本:
it('should update record', async () => {
await spec()
.post('http://localhost:3000/user')
.withJson({
"name": "helen",
"city": "London"
})
.useInteraction({
request: {
method: 'GET',
path: 'https://62b32eab4f851f87f4563d9b.mockapi.io/user/32'
},
response: {
status: 200,
body: [
{"name":"Jerald Labadie","country":"Buckinghamshire","city":"Lake Junebury","email":"Alf_Schneider81@gmail.com","id":"32"}
]
}
})
.expectStatus(200)
.wait(3000)
})我知道我可以连接到mockapi的模拟,但有什么办法解决这个问题,并在本地这样做吗?
发布于 2022-06-23 05:10:07
在使用模拟时,我们需要将流量从您的服务转移到本地模拟服务器。可以简单地使用环境变量来实现。
const mock_url = process.env.MOCK_URL || 'https://<key>.mockapi.io';现在,通过将MOCK_URL环境变量初始化到pactum的模拟服务器url来启动服务器。假设pactum模拟服务器在本地主机9393上运行。
export MOCK_URL=http://localhost:9393 && node server.js现在更新您的交互以处理流量。
it('should update record', async () => {
await spec()
.useInteraction({
request: {
method: 'GET',
path: '/user/32'
},
response: {
status: 200,
body: [ {"name":"Jerald Labadie","country":"Buckinghamshire","city":"Lake Junebury","email":"Alf_Schneider81@gmail.com","id":"32"} ]
}
})
.post('http://localhost:3000/user')
.withJson({
"name": "helen",
"city": "London"
})
.expectStatus(200)
})https://stackoverflow.com/questions/72718419
复制相似问题