玩笑的Expect.objectContaining()在Expect.toHaveBennCalled()中失败

时间:2019-10-11 10:59:51

标签: javascript node.js typescript jestjs aws-sdk

我正在尝试编写一个测试,以测试使用aws-sdk写入DynamoDB的代码。尽管官方文档(https://jestjs.io/docs/en/expect#expectobjectcontainingobject)中提供了非常相似的用例,但我的断言失败了。任何帮助表示赞赏。

这是我的测试

test("givenCprRepositoryServiceTestSuite_whenSaveCprRecord_thenMetaExpiresAtAppended", async () => {
        await cprRepositoryService.saveCprRecord({cprNumber: existingCpr, firstName: "Jens", lastName: "Jensen"})

        expect(aws.DynamoDB.DocumentClient.prototype.put).toHaveBeenCalledWith(
            expect.objectContaining({
                Item: {
                    metaExpiresAt: expect.any(Number)
                }
            }))
    })

返回的错误是:

错误:  expect(jest.fn()).toHaveBeenCalledWith(...expected)

预期的ObjectContaining:

{"Item": {"metaExpiresAt": Any<Number>}}

已收到:

{"Item": {"cprNumber": "1234567890", "firstName": "Jens", "lastName": "Jensen", "metaExpiresAt": 1570792526}, "TableName": "CountryLayer_Cpr"}

1 个答案:

答案 0 :(得分:0)

expect.objectContaining(object)方法无法处理嵌套对象。要解决此问题,建议对您的代码进行以下修改。

test("givenCprRepositoryServiceTestSuite_whenSaveCprRecord_thenMetaExpiresAtAppended", async () => {
        await cprRepositoryService.saveCprRecord({cprNumber: existingCpr, firstName: "Jens", lastName: "Jensen"})

        expect(aws.DynamoDB.DocumentClient.prototype.put).toHaveBeenCalledWith(
            expect.objectContaining({
                Item: expect.objectContaining({
                    metaExpiresAt: expect.any(Number)
                })
            }))
    })