我正在尝试为没有任何框架的纯JavaScript编写测试。我正在使用Jest进行测试,但正在努力访问HTML正文(及其中的元素)并进行操作。当我尝试在普通的JavaScript文件中获取DOM元素时(当我运行“ npm start”时),访问没有问题。但是,当我尝试在测试文件中使用DOM元素(带有“ npm test”)来进行console.log时,我得到的是一个空文档。
您对解决此问题有何建议?
我尝试了两种解决方案。首先,我使用了以下来源:https://dev.to/snowleo208/things-i-learned-after-writing-tests-for-js-and-html-page-4lja在这种情况下,我可以访问我的DOM元素,但是当我尝试使用fireEvent更改某些内容时,没有任何反应。
test.js:
import { screen } from '@testing-library/dom'
const fs = require('fs');
const path = require('path');
let html = fs.readFileSync(path.resolve(__dirname, './view/index.html'), 'utf8');
document.documentElement.innerHTML = html.toString();
jest
.dontMock('fs');
const input = document.getElementById('input')
const button = document.getElementById('button')
test('Clicking on Insert button should show alert message', () => {
fireEvent.change(input, { target: { value: 'horse' } })
fireEvent.click(button, { button: '0' })
screen.debug()
console.log(document.body.innerHTML)
})
第二个解决方案是使用Jest加Selenium来运行Web服务器。在这种情况下,服务器可以正常运行,但是无法访问DOM元素。我在这里做什么错了?
test.js:
import { fireEvent, cleanup, screen } from '@testing-library/dom'
import '@testing-library/jest-dom/extend-expect'
import {Builder, By} from 'selenium-webdriver'
import chrome from 'selenium-webdriver/chrome'
import chromedriver from 'chromedriver'
import regeneratorRuntime from "regenerator-runtime"
import script from "jest"
const url = 'http://localhost:8000'
let driver
chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build())
const options = new chrome.Options()
options.addArguments(
'headless'
)
describe('List View', () => {
jest.setTimeout(10000)
beforeAll((done) => {
driver = new Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build()
driver.get(url).then(()=>{
console.log("Got page")
done()
})
})
beforeEach(async () => {
await driver.navigate().refresh();
})
afterAll(async () => {
await driver.quit();
}, 15000);
it('Clicking on Insert button should show alert message', async function(){
console.log(document.body.innerHTML)
let button = await driver.findElement(By.id("button"))
screen.debug()
})
});
我的文件结构的一部分: package.json
"start": "node app.js",
"test": "cross-env NODE_ENV=test ./node_modules/.bin/jest test --verbose --env=jsdom --testResultsProcessor ./node_modules/jest-junit"
app.js
...
app.use(express.static(path.join(__dirname, 'view')));
app.listen(8000, '0.0.0.0', function() {});
module.exports = app;
view / index.html
<body>
<input id="input" type="text"></input>
<button id="button">Insert</button>
<ul id="list"></ul>
<script type="module" src="js/script.js"></script>
</body>
view / js / script.js-我的JavaScript文件