我做了一个简单的测试来检查背景颜色是否改变
/**
* @jest-environment jsdom
*/
const fs = require('fs');
const path = require('path');
const html = fs.readFileSync(path.resolve(__dirname, '../index.html'), 'utf8');
describe('Testing script.js', () => {
let js
beforeEach(()=>{
document.documentElement.innerHTML = html.toString();
js = require('../script');
})
afterEach(() => {
document.documentElement.innerHTML = '';
});
test('Button click changes output content', () => {
const myButton1 = document.getElementById('button-test1')
const output = document.getElementById('output')
const outputBefore = output.textContent
myButton1.click()
const outputAfter = output.textContent
expect(outputBefore).not.toBe(outputAfter)
});
test('changes background colour', () => {
const myButton2 = document.getElementById('button-test2')
document.body.style.backgroundColor = 'blue'
const bodyBefore = document.body.style.backgroundColor
console.log(bodyBefore)
myButton2.click()
const bodyAfter = document.body.style.backgroundColor
console.log(bodyAfter)
expect(bodyBefore).not.toBe(bodyAfter)
});
});
const myButton1 = document.getElementById('button-test1')
const myButton2 = document.getElementById('button-test2')
myButton1.addEventListener('click', () => clickEvent1())
myButton2.addEventListener('click', () => clickEvent2())
function clickEvent1() {
console.log("clickEvent1")
const element = document.getElementById('output')
if (element.textContent === "") element.textContent = "Hello World"
}
function clickEvent2() {
console.log("clickEvent2")
if (document.body.style.backgroundColor != 'red') document.body.style.backgroundColor = 'red'
}
第二个测试失败了,但是当单独运行时,测试工作正常。起初我认为这是因为同一个按钮被点击了两次,但这些是单独的元素。我不认为测试本身有问题,我无法解决。
我尝试了before每一个/后每一个()拆解html,希望在测试之间“重置”JSDOM。
这对我来说毫无意义,也打破了我对Jest工作原理的理解。
有人能解释这种行为吗?
你不需要事后,这才是问题所在