【问题标题】:How do I check that the correct objects are being returned via a function (expect function returns [Function Anonymous])?如何检查是否通过函数返回了正确的对象(期望函数返回 [Function Anonymous])?
【发布时间】:2022-08-17 01:10:43
【问题描述】:

我有一个功能:

const sort = 
        (pets,attribute) =>
                _(pets)
                .filter(pets=> _.get(pets, attribute) !== null)
                .groupBy(attribute)
                .value()

一些数据:

const pets= [{
    id: 1,
    name: \'snowy\',
    },
    {
    id: 2,
    name: \'quacky\',
    },
    {
    id: 3,
    name: \'snowy\',
    age: 5,
    },
    {
    id: null,
    name: null,
    age: null
    }
]

const attribute = \'name\'

我目前正在尝试为此编写一些 Jest 单元测试,以测试函数在根据属性排序后是否返回正确的结果对象。 的结果: sort(pets,attribute) 是这样的:

{
  snowy: [ { id: 1, name: \'snowy\' }, { id: 3, name: \'snowy\', age: 5} ],
  quacky: [ { id: 2, name: \'quacky\' } ]
}

有没有办法我可以做一个 expect 来匹配两个对象 snowyquacky 这里? 我要测试的是对象是否按键正确分组。

我尝试过使用类似的东西

const res = arrangeBy(users,key)
    expect(res).toEqual(
        expect.arrayContaining([
            expect.objectContaining({\'snowy\' : [ { id: 1, name: \'snowy\' }, { id: 3, name: \'snowy\', age: 5 } ]},
            expect.objectContaining({\'quacky\' : [ { id: 2, name: \'quacky\' } ]}))
        ])
    )

这似乎不起作用,接收到的输出似乎输出:

    Expected: ArrayContaining [ObjectContaining {\"snowy\": [{\"id\": 1, \"name\": \"snowy\"}, {\"age\": 5, \"id\": 3, \"name\": \"snowy\"}]}]
    Received: [Function anonymous]

我不确定测试这种功能的最佳方法是什么,因此不胜感激。

    标签: javascript jestjs lodash


    【解决方案1】:

    如果这是您的 arrangeBy() 返回的内容:

    {
      snowy: [ { id: 1, name: 'snowy' }, { id: 3, name: 'snowy', age: 5} ],
      quacky: [ { id: 2, name: 'quacky' } ]
    }
    

    然后你可以这样做:

    const expected = {
      snowy: [ { id: 1, name: 'snowy' }, { id: 3, name: 'snowy', age: 5} ],
      quacky: [ { id: 2, name: 'quacky' } ]
    }
    
    const res = arrangeBy(users,key)
    expect(res).toEqual(expected)
    

    但是看着你的错误信息,我猜你还有别的东西混淆了。一开始你列出了一个sort 函数的实现,它似乎没有在测试中使用。 arrangeBy 从现在开始在哪里。

    请提供更多代码示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-07
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2021-03-06
      • 2021-07-11
      相关资源
      最近更新 更多