如何为普通JavaScript函数编写快照测试?
我编写了一个函数,在单击按钮时向按钮添加一个类:如何为普通JavaScript函数编写快照测试?,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,我编写了一个函数,在单击按钮时向按钮添加一个类: export default function () { const button = document.getElementById('button'); button.addEventListener('click', ((event) => { event.target.classList.add('is-active'); })); }; 我想写一封信。但所有的例子都提到了反应。我很难将示例翻译成普通的Java
export default function () {
const button = document.getElementById('button');
button.addEventListener('click', ((event) => {
event.target.classList.add('is-active');
}));
};
我想写一封信。但所有的例子都提到了反应。我很难将示例翻译成普通的JavaScript
如何为上述函数编写快照测试?要进行设置,请将按钮添加到DOM并初始化
initButton()
函数。然后单击按钮并在快照上断言
import initButton from './button';
it('should add class to button when clicked', () => {
document.body.innerHTML = '<button id="button">Click me!</button>';
initButton();
document.getElementById('button').click();
expect(document.body).toMatchSnapshot();
});
import initButton from./button';
它('单击时应将类添加到按钮',()=>{
document.body.innerHTML='单击我!';
initButton();
document.getElementById('button')。单击();
expect(document.body).toMatchSnapshot();
});
快照将输出:
exports[`should add class to button when clicked 1`] = `
<body>
<button
class="is-active"
id="button"
>
Click me!
</button>
</body>
`;
exports[`单击1``时应将类添加到按钮]=`
点击我!
`;