Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jest测试将返回值作为哈希的子集进行匹配-不调用函数两次?_Javascript_Jestjs - Fatal编程技术网

Javascript jest测试将返回值作为哈希的子集进行匹配-不调用函数两次?

Javascript jest测试将返回值作为哈希的子集进行匹配-不调用函数两次?,javascript,jestjs,Javascript,Jestjs,我希望将函数返回值的数据结构与更大的结构相匹配(即,返回的结构与更完整的散列“验证”)。我有一个使用toHaveProperty的工作测试,但我不想在这个特定问题的测试中定义我的对象结构 我真正想要的是能够让我测试包含在较大散列中的结构(而不是值),并找到不调用函数两次的方法: // ** this would fail if a property value is different ** test('thing returns something matching the structure

我希望将函数返回值的数据结构与更大的结构相匹配(即,返回的结构与更完整的散列“验证”)。我有一个使用toHaveProperty的工作测试,但我不想在这个特定问题的测试中定义我的对象结构

我真正想要的是能够让我测试包含在较大散列中的结构(而不是值),并找到不调用函数两次的方法:

// ** this would fail if a property value is different **
test('thing returns something matching the structure within types', () => {
    expect(thing()).toBeDefined(
        expect(types).toMatchObject(thing())
    );
});
结构如下:

var types = {
    changeSheet:{
        command: ["s", "sheet"],
        options: [],
        required: [],
        sheet_option: true,
    },
    checkIn:{
        command: ["in", "i"],
        options: ["-a", "--at"],
        required: [],
        sheet_option: false,
    },
    checkOut:{
        command: ["out", "o"],
        options: ["-a", "--at"],
        required: [],
        sheet_option: true,
    }
};
下面是我想要测试的函数:

function thing() {
    return {changeSheet: {
        command: ["s", "sheet"],
        options: [],
        required: [],
        sheet_option: false,
    }};
}

请注意changeSheet.sheet_选项与返回值与“类型”散列不同。是否有jest匹配机制可以检查我的结构并忽略值,或者我是否坚持使用toHaveProperty()?

您可以使用jest的
expect
匹配工具:


也就是说,您在这里测试的只是结构/类型,使用静态类型检查器(如TypeScript或Flow)可能会更好。

您可以使用Jest的
expect
匹配工具:


也就是说,您在这里测试的只是结构/类型,使用静态类型检查器(如TypeScript或Flow)可能会更好。

好的,这很有意义,您已经向我指出,我根本没有测试值类型。我真的只是想用“类型”作为键名的模板。事后看来,如果不检查值类型,这有点愚蠢。我来自强类型语言的背景,因此,是的,我可能会在这里对javascript世界进行一些调整。谢谢!好的,这是有道理的,您已经向我指出,我根本没有测试值类型。我真的只是想用“类型”作为键名的模板。事后看来,如果不检查值类型,这有点愚蠢。我来自强类型语言的背景,因此,是的,我可能会在这里对javascript世界进行一些调整。谢谢!
expect(thing()).toMatchObject({
  changeSheet: {
    command: expect.arrayContaining([
      expect.any(String),
      expect.any(String)
    ]),
    options: expect.any(Array),
    required: expect.any(Array),
    sheet_option: expect.any(Boolean)
  }
});