开玩笑toMatchObject抛出TypeError

时间:2018-08-06 11:40:00

标签: javascript node.js jestjs

我正在使用Jest测试我的节点应用程序,以下情况验证了一些数据已添加到数据库中(考虑到DB逻辑可以正常工作):

it("should add empty string hooks if none added", async () => {
    const item = { type: "type" };

    await DB.insert({ item });

    const fetch = await DB.fetch({ type: "type" });

    expect(fetch.data.items).toHaveLength(1);
    expect(typeof fetch.data.items[0]).toEqual("object");
    expect(fetch.data.items[0]).toMatchObject({
        ...item,
        preHook: "",
        postHook: "",
        otherField: expect.anything(),
        // ... other fields created by DB might go here
    });
});

运行npm test时得到以下结果:

FAIL  test/server/server.test.jsal
  ● Database › Items › should add empty string hooks if none added

    TypeError: Cannot read property 'prototype' of undefined

      236 |             expect(fetch.data.items).toHaveLength(1);
      237 |             expect(typeof fetch.data.items[0]).toEqual("object");
    > 238 |             expect(fetch.data.items[0]).toMatchObject({
          |                                             ^
      239 |                 ...item,
      240 |                 preHook: "",
      241 |                 postHook: ""

      at _callee17$ (test/server/server.test.js:238:45)
      at tryCatch (node_modules/regenerator-runtime/runtime.js:65:40)
      at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:303:22)
      at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:117:21)
      at step (test/server/server.test.js:7:191)
      at test/server/server.test.js:7:361

正在使用的包裹:

"babel-jest": "^23.4.0"
"@types/jest": "^23.3.0"
"jest": "^23.4.1"
"jest-enzyme": "^6.0.2"
"jest-transform-graphql": "^2.1.0"

这很奇怪,因为我在其他文件中使用了相同的匹配器,并且效果很好,例如:

it("should return all templates for a Postgres datasource", () => {
    const templates = getTemplatesForDataSource(
        { type: DataSourceType.Postgres }
    );

    expect(templates).toMatchObject({
        requestMappingTemplates: {
            Custom: "",
            "Postgres Query": expect.any(String)
        },
        responseMappingTemplates: {
            Custom: "",
            "Postgres Response": expect.any(String)
        }
    });
});

你知道这是怎么回事吗?

1 个答案:

答案 0 :(得分:0)

fetch.data.items[0]没有原型。我的猜测是,开玩笑的toMatchObject需要一个原型并且失败了。我可以看到Jest提起了一个有关您“竖起大拇指”的问题:https://github.com/facebook/jest/issues/6730

在此期间,您可以使用Jest的toEqual匹配器。它不需要对象具有原型。