gpt4 book ai didi

javascript - 开 Jest toMatchObject 会抛出 TypeError

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:13 25 4
gpt4 key购买 nike

我正在使用 Jest 来测试我的 Node 应用程序,以下情况验证了一些数据已添加到数据库中(考虑 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)
}
});
});

知道这里发生了什么吗?

最佳答案

fetch.data.items[0] 没有原型(prototype)。我的猜测是,在幕后 jest 的 toMatchObject 需要原型(prototype)并失败。我可以看到 Jest 提交了一个关于它的问题,您已经“竖起了大拇指”:https://github.com/facebook/jest/issues/6730

同时,您可以使用 Jest 的 toEqual 匹配器。它不要求对象具有原型(prototype)。

关于javascript - 开 Jest toMatchObject 会抛出 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51706800/

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