【发布时间】:2019-01-28 10:01:54
【问题描述】:
首先:据我所知,这不是重复的。其他类似问题的问题都略有不同,例如使用像 babel 这样的转换,或者在传递导入方面存在问题。就我而言,我没有转换,我有一个测试文件和一个将被测试的文件导入文件。我刚开始使用 jest 并使用默认设置,所以没有配置文件可以发布。
当我尝试运行测试时,我收到错误消息:
测试套件无法运行
Jest 遇到了意外的令牌
这通常意味着您正在尝试导入 Jest 无法解析的文件,例如它不是纯 JavaScript。
测试文件:
export function showTooltip(x, y, content) {
const infoElement = document.getElementById('info');
infoElement.style.left = `${x}px`;
infoElement.style.top = `${y}px`;
infoElement.style.display = 'block';
infoElement.innerText = createTooltipText(content);
}
function createTooltipText(object) {
return Object.keys(object)
.filter(key => key != 'id')
.map(key => `${key} : ${object[key]}`)
.join('\n');
}
export function hideTooltip() {
const infoElement = document.getElementById('info');
infoElement.style.display = 'none';
}
测试:
import {showTooltip, hideTooltip} from '../../../src/public/javascripts/tooltip.js';
const TOOLTIP_DUMMY = {
style: {
left: 0,
top: 0,
display: '',
innerText: ''
}
};
test('showTooltip accesses the element with the id \'info\'', () => {
const getElementByIdMock = jest.fn(() => TOOLTIP_DUMMY);
document.getElementById = getElementByIdMock;
showTooltip(0, 0, {});
expect(getElementByIdMock).toHaveBeenCalledWith('info');
});
test('hideTooltip accesses the element with the id \'info\'', () => {
const getElementByIdMock = jest.fn(() => TOOLTIP_DUMMY);
document.getElementById = getElementByIdMock;
hideTooltip();
expect(getElementByIdMock).toHaveBeenCalledWith('info');
});
如您所见,我使用的是纯 javascript,所以我不确定在这里做什么。错误消息提供了关于 Babel 的进一步提示,这并不真正适用于我的情况。
旁注:我的测试可能有缺陷。我目前正在尝试弄清楚如何使用模拟来避免与文档的交互,但我不确定这是否是这样。然而,这不是这个问题的重点,因为它不应该影响测试的运行能力,但我非常愿意接受建议。
编辑:为什么这不是 this question 的重复:有点像,但我觉得这个问题和接受的答案对我并没有真正的帮助,希望有人能从中受益一个。
【问题讨论】:
标签: javascript jestjs