代码之家  ›  专栏  ›  技术社区  ›  dotnetCarpenter

松散匹配中的一个值开玩笑的

  •  1
  • dotnetCarpenter  · 技术社区  · 6 年前

    我有一个分析追踪器,只会调用后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 但是我没有看到任何对我的用例有用的东西。

    2 回复  |  直到 6 年前
        1
  •  82
  •   Roman Usherenko    5 年前

    这可以通过非对称匹配器来实现(在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)
      })
    )
    
        2
  •  26
  •   Herman Starikov    6 年前

    track.mock.calls[0][0] (第一 [0] 是调用号,第二个 toMatchObject 找到部分匹配的对象,避免动态参数,如 intervalInMilliseconds .