gpt4 book ai didi

jestjs - 松散匹配 jest.toHaveBeenCalledWith 中的一个值

转载 作者:行者123 更新时间:2023-12-02 11:14:11 25 4
gpt4 key购买 nike

我有一个分析跟踪器,它只会在 1 秒后调用一个对象,其中 intervalInMilliseconds (持续时间)值为 不是 确定性的。

我如何使用 jest.toHaveBeenCalledWith测试对象?

 test('pageStats - publicationPage (will wait 1000ms)', done => {
const track = jest.fn()

const expected = new PayloadTiming({
category: 'PublicationPage',
action: 'PublicationPage',
name: 'n/a',
label: '7',
intervalInMilliseconds: 1000 // or around
})

mockInstance.viewState.layoutMode = PSPDFKit.LayoutMode.SINGLE
const sendPageStats = pageStats({
instance: mockInstance,
track,
remoteId: nappConfig.remoteId
})

mockInstance.addEventListener('viewState.currentPageIndex.change', sendPageStats)

setTimeout(() => {
mockInstance.fire('viewState.currentPageIndex.change', 2)

expect(track).toHaveBeenCalled()
expect(track).toHaveBeenCalledWith(expected)

done()
}, 1000)

expect(track).not.toHaveBeenCalled()
})
expect(track).toHaveBeenCalledWith(expected)失败:
Expected mock function to have been called with:
{"action": "PublicationPage", "category": "PublicationPage", "intervalInMilliseconds": 1000, "label": "7", "name": "n/a"}
as argument 1, but it was called with
{"action": "PublicationPage", "category": "PublicationPage", "intervalInMilliseconds": 1001, "label": "7", "name": "n/a"}

我看过 jest-extended
但我没有看到任何对我的用例有用的东西。

最佳答案

这可以通过非对称匹配器来完成(在 Jest 18 中引入)

expect(track).toHaveBeenCalledWith(
expect.objectContaining({
"action": "PublicationPage",
"category": "PublicationPage",
"label": "7",
"name": "n/a"
})
)

如果您使用 jest-extended你可以做类似的事情

expect(track).toHaveBeenCalledWith(
expect.objectContaining({
"action": "PublicationPage",
"category": "PublicationPage",
"label": "7",
"name": "n/a",
"intervalInMilliseconds": expect.toBeWithin(999, 1002)
})
)

关于jestjs - 松散匹配 jest.toHaveBeenCalledWith 中的一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52337116/

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