gpt4 book ai didi

javascript - 测试一个函数在 promise 解析中被调用

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

我正在构建一个应用程序,我需要在其中测试回调函数是否已在 promise 解析中调用。

实际上,我有以下代码:

const callbackRender = (httpResponse, response) => {
if (httpResponse.content.content) response.send(httpResponse.content.content)
else response.render(httpResponse.content.page)
}

const callback = (injector, route) => {
return (request, response) => {
const ctrl = injector.get(route.controller)
const result = ctrl[route.controllerMethod](new HttpRequest())
if (result.then) {
result.then(res => {
console.log('hey I m in !')
callbackRender(res, response)
})
} else {
callbackRender(result, response)
}
}
}

我需要测试

result.then(res => {
console.log('hey I m in !')
callbackRender(res, response)
})

名副其实。

我使用 mocha 和 chai 编写了这个测试,我总是有 0 次 spy 调用:

it('should call the callback render method when httpResponse is a promise', (done) => {
const mock = sinon.mock(injector)
const ctrl = new UserControllerMock()
const routes = routeParser.parseRoutes()
mock.expects('get').returns(ctrl)
const spy = chai.spy(callbackRender)
callback(injector, routes[3])(request, response)
setTimeout(() => {
expect(spy).to.have.been.called.once
mock.verify()
mock.restore()
done()
}, 0)
})

注意:如果调用得当,promise resolve 部分中的日志消息,我可以将其显示在屏幕上。

有什么想法吗?

最佳答案

返回您的响应,然后您可以在测试中调用then

const callback = (injector, route) => {
return (request, response) => {
const ctrl = injector.get(route.controller)
const result = ctrl[route.controllerMethod](new HttpRequest())
if (result.then) {
return result.then(res => {
callbackRender(res, response)
});
} else {
return Promise.resolve(callbackRender(result, response));
}
}
}

你的测试:

it('should call the callback render method when httpResponse is a promise', (done) => {
const mock = sinon.mock(injector)
const ctrl = new UserControllerMock()
const routes = routeParser.parseRoutes()
mock.expects('get').returns(ctrl)
const spy = chai.spy(callbackRender)
callback(injector, routes[3])(request, response).then(() => {
expect(spy).to.have.been.called.once
mock.verify()
mock.restore()
done()
});
});

虽然,您似乎没有注入(inject) callbackRender,所以您的 spy 可能仍未被调用。

关于javascript - 测试一个函数在 promise 解析中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37678246/

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