【发布时间】:2019-06-27 15:03:33
【问题描述】:
我是 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] 数组中没有问题但在测试中没有问题?
【问题讨论】:
-
您是否使用调试器逐步完成了测试代码?
-
当您执行
require时,最后可能还需要.default。 comment-posted-as-answer 还建议使用普通的import--但检查您的假设始终是第一步,例如,确保您正在操作您认为自己的数据. -
发生的事情是我实际上将 JSON 文件的特定段传递到实际函数中,但没有进行测试。始终确保您的测试实际上是在测试您的函数所采用的参数!我应该删除这个问题吧?