首页 > 解决方案 > 在 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 框架的机制?

标签: javascripttypescriptunit-testingazure-functions

解决方案


如果您想在作业中抛出错误:

context.bindings.cosmosDocument = JSON.stringify(body);

你有两个选择:

  1. 保留context.bindingsundefined,这将导致TypeError: Cannot set property 'cosmosDocument' of undefined; 或者

  2. 实现一个抛出您选择的错误的set访问器:

    context.bindings = {
      set cosmosDocument(document: string) {
        throw new Error("");
      },
    };
    

推荐阅读