javascript - 在 TypeScript 中测试对象分配
问题描述
我正在编写一个 Azure 函数并将数据持久化到 CosmosDB。它是这样工作的:
const preloadShipmentTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
if (req.body) {
const body: Body = req.body
context.bindings.cosmosDocument = JSON.stringify(body);
context.res = {
status: 200,
body: 'Successfully persisted document'
};
}
}
这是对相同功能的测试:
test('returns 200', async () => {
let contextMock: Context = mock<Context>()
const body = createBody()
const request = {
body: body
}
let context = instance(contextMock)
context.bindings = {
cosmosDocument: undefined
}
await httpFunction(context, request)
verify(contextMock.log(`log`)).once()
expect(context.bindings.cosmosDocument).toBeDefined()
expect(context.bindings.cosmosDocument).toEqual(JSON.stringify(body))
expect(context.res).toBeDefined()
expect(context.res!.status).toBe(200)
expect(context.res!.body).toBe('Successfully persisted document')
})
对象中的绑定在Context
定义中如下所示:
/**
* Input and trigger binding data, as defined in function.json. Properties on this object are dynamically
* generated and named based off of the "name" property in function.json.
*/
bindings: {
[key: string]: any;
};
我为此使用 ts-mockito。
现在我想测试当对象分配失败时会发生什么,例如写入数据库失败:
when(context.bindings.cosmosDocument).thenThrow(new Error(''))
显然这不起作用,因为 cosmosDocument 不是模拟:
TypeError:this.methodToStub 不是函数
我怎样才能在 TypeScript 中做到这一点?重新排列我的代码是一件简单的事情,还是我必须深入研究 Azure Function 框架的机制?
解决方案
如果您想在作业中抛出错误:
context.bindings.cosmosDocument = JSON.stringify(body);
你有两个选择:
保留
context.bindings
为undefined
,这将导致TypeError: Cannot set property 'cosmosDocument' of undefined
; 或者实现一个抛出您选择的错误的
set
访问器:context.bindings = { set cosmosDocument(document: string) { throw new Error(""); }, };
推荐阅读
- javascript - 为什么 `number |= 0` 会转换为 32 位整数?
- google-calendar-api - 为 Squarespace 上的活动嵌入带有颜色的 Google 日历
- mongodb - 使用匹配元素更新子子文档的数组
- c - 如何在 C 中使用 GTK 使用 G_CALLBACK 获取输入值
- apache-httpcomponents - 如何在 Apache HttpAsyncClientBuilder 中禁用会话 cookie
- reactjs - React:进行自己的 A/B 测试
- angular - 使用 Angular/Typescript 6 框架访问 YouTube 数据 API 不返回数据
- go - 接口的结构嵌入,恐慌:运行时错误
- python - Python 精度处理
- nginx - Nginx 404 不工作,重定向到主页