我是Jest的新手,目前只是对现有功能进行一些测试。 我有一个函数,该函数需要一个数据数组(来自JSON文件),并将其映射到特定位置并绘制点。
这是函数plotPoints:
function plotPoints(data) {
console.log(data.subset[0]);
const sub0 = data.subset[0];
...
plotPoints将JSON数据作为参数。该功能起作用是因为它可以在控制台中正确记录数据,而其他功能则可以正常工作。
但是测试总是失败:
plotPoints.test.js
import plotPoints from '../functions/plotPoints';
const dataSrc = require('../../public/data/jsonfile.json');
test('it finds the plot data', () => {
expect(plotPoints(dataSrc)).toBeDefined();
});
返回此错误:
it finds the plot data
TypeError: Cannot read property '0' of undefined
3 | // takes raw JSON data and builds a big object with matching joint pairs
4 | function plotPounts(data) {
> 5 | const sub0 = data.subset[0];
| ^
6 |
at plotPoints (src/functions/plotPoints.js:5:16)
at Object.<anonymous>.test (src/tests/plotPoints.test.js:5:10)
我认为该功能可能是在加载jsonfile.json之前在测试中运行的,所以我尝试根据Jest文档编写异步测试:
test('it finds the correct joints', done => {
function callback(input) {
expect(input).toBeDefined();
done();
}
mapJoints(callback(dataSrc));
});
但这没什么区别。有什么理由可以使函数在data.subset[0]
数组中找到但在测试中没有找到问题?
答案 0 :(得分:0)
您是否检查了dataSrc
是否已定义?
尝试将require替换为:
import dataSrc from '../../public/data/jsonfile.json'