问题描述
我已经尝试了几种方法来解决我正在使用 jest.mock(...)
和 jest.spyOn(...)
解决的当前问题,但到目前为止都没有成功。
让我提供一些我目前所拥有的背景
在我的 contorller.ts 中,我正在拨打电话以恢复决策
.....
.....
this.router.post('/decision',decisionMiddleware,this.finalDecision)
.....
.....
private finalDecision(){
const finalDecision = req.decision;
// do something further with the decision here
}
在我的中间件 decisionMiddleware.ts
中,我进行了 fetch 调用并使用来自 fetch 的响应填充请求对象
async decisionMiddleware(req,res,next){
....
....
const decisionRes = await fetch(url,req.body);
req.decision = decisionRes; // I want to mock the data that gets populated here
next()
......
......
}
export default decisionMiddleware;
在我的测试文件controller.test.ts
import request from 'supertest';
import App from '../../app';
import Controller from '../controller';
....
....
describe('run test',() => {
let app: App;
let controller: Controller;
beforeAll(() => {
let tenant = "Sample Tenant";
controller = new Controller();
app = new App(tenant,[controller]);
});
describe('Check Decision',() => {
const samplePayload = {
"payload":{.....}
};
it("checking opa for accepted permission",async () => {
const res = await request(app.getServer())
.post(`/decision`).send(samplePayload);
expect(res.status).toBe(200);
expect(res.body).toHaveProperty("decision_id");
expect(res.body).toHaveProperty("result");
expect(res.body).toHaveProperty("result.allow",true);
})
})
对于上述我想强制响应在正文中具有指定的属性并且状态为 200。我通过在顶级声明尝试了以下内容,但没有成功
jest.mock('../../middleware/decision.middleware',() => {
jest.fn((req,next) => {
req.body = {
"decision_id": "580ae1ff-f335-4382-8207-f5094aba59b9","result":{
"allow": true
}
}
next();
})
})
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)