【发布时间】:2021-04-03 15:51:34
【问题描述】:
我有以下功能:
要测试的代码
export default function main() {
const createAndAppendPTag = () => {
const p = document.createElement('p');
document.body.appendChild(p);
};
window.document.addEventListener('click', () => {
createAndAppendPTag();
});
}
问题是:如何使用 Jest 断言 createAndAppendPTag 在文档点击事件中被调用?
开玩笑
这是我尝试过的,但似乎无法通过测试:
import main from './main'
window.document.addEventListener = jest.fn();
const createAndAppendPTag = jest.fn();
describe('Main', () => {
const documentClickEvent = new Event('click');
test('appends p tag to the document', () => {
// dispatching event before and after invoking `main` to be sure
window.document.dispatchEvent(documentClickEvent);
main();
window.document.dispatchEvent(documentClickEvent);
expect(window.document.addEventListener).toHaveBeenNthCalledWith(1, 'click', () => {});
expect(createAndAppendPTag).toHaveBeenCalledTimes(1);
});
});
终端
这会导致以下结果:
???? Main › appends p tag to the document
expect(jest.fn()).toHaveBeenNthCalledWith(n, ...expected)
n: 1
Expected: "click", [Function anonymous]
Number of calls: 0
5 | main();
6 | window.document.dispatchEvent(documentClickEvent);
> 7 | expect(window.document.addEventListener).toHaveBeenNthCalledWith(1, 'click', () => {});
* | ^
提前致谢。
【问题讨论】:
-
createAndAppendPTag是 main 私有的,因此您在测试时看不到它。你能简单地直接测试副作用吗(p被添加到正文中)? -
感谢@terrymorse 的建议,过去一个小时左右我一直在尝试这样做,但没有运气,看来我需要稍后再问一个关于在测试中查询 dom 的问题,因为我身体越来越空虚,在那之前也许有人可以提供另一个建议/解决方案。
标签: javascript unit-testing jestjs