我在NodeJS API中使用Jest进行单元测试。我已经安装了jest并将其添加到package.json中的脚本中。但是面对这个问题:
FAIL api / test / math.test.js ●测试套件无法运行
TypeError: Cannot read property 'prototype' of undefined
at module.exports (node_modules/request-promise-core/configure/request2.js:34:48)
at Object.<anonymous> (node_modules/request-promise-native/lib/rp.js:15:1)
at Object.<anonymous> (node_modules/jsdom/lib/api.js:6:17)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.091s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! chain-analytics@1.0.0 test: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sample-project@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
下面是我的示例类:
math.js:
const sum = (a, b) => a + b
const mul = (a, b) => a * b
const sub = (a, b) => a - b
const div = (a, b) => a / b
export default { sum, mul, sub, div };
math.test.js:
const {sum, mul, sub, div} = require("./math")
test("Adding 1 + 1 equals 2", () => {
expect(sum(1, 1)).toBe(2)
})
test("Multiplying 1 * 1 equals 1", () => {
expect(mul(1, 1)).toBe(1)
})
test("Subtracting 1 - 1 equals 0", () => {
expect(sub(1, 1)).toBe(0)
})
test("Dividing 1 / 1 equals 1", () => {
expect(div(1, 1)).toBe(1)
})
任何建议都值得赞赏。谢谢!
答案 0 :(得分:1)
将math.js
中的出口更改为:
module.exports = { sum, mul, sub, div };
我相信NodeJS不支持ES6导入/导出语法。
答案 1 :(得分:1)
导出使用导入。 module.exports
会给您require
。
模块和要求
您应该更改math.js
:
module.exports = { sum, mul, sub, div };
对于代码:
const {sum, mul, sub, div} = require("./math");
导入/导出
或者您应该使用:
import { sum, mul, sub, div } from "./math";
对于代码:
export default { sum, mul, sub, div };
这是正确的组合。
答案 2 :(得分:0)
q.js
:
function sum(a, b) {
return a + b;
}
module.exports = sum;
q.test.js
:
const sum = require('../src/q');
test('adds 1 + 2 to equal 3', () => {
const result = sum(1, 3);
expect(result).toBe(3);
});
即使给出错误,也完全从jest
文档中复制了此错误!
https://jestjs.io/docs/en/getting-started