我有 index.html 文件,h1 中包含“Hello world!”文本:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<meta charset="UTF-8">
</head>
<body>
<h1>Hello world!</h1>
<script src="bundle.js"></script>
</body>
</html>
这是我的 index.test.js:
import {expect} from 'chai';
import jsdom from 'jsdom';
import fs from 'fs';
describe('index.html', () => {
it("should say 'Hello world!'", () => {
// read file content to variable
const index = fs.readFileSync('./src/index.html', "utf-8");
// pass this variable to jsdom:
jsdom.env(index, function(err, window) {
const h1 = window.document.getElementByTagName('h1')[0]; // read our h1
expect(h1.innerHTML).to.equal("Helloooooooo World!"); //<---- passed
done();
window.close();
});
})
})
我保存所有并像这样运行它:
"test": "mocha --reporter progress buildScripts/testSetup.js \"src/**/*.test.js\""
它总是报告“通过”。
我什至可以评论 expect
字符串,它也通过了 oO
最佳答案
您需要将done
声明为it
的参数。
it('Does x', (done) => {
someAsyncFunc((err, result) => {
done()
})
})
通过声明第一个参数,您实质上告诉 mocha 等待直到 done
被调用,否则它只是将其视为同步测试
因此,它不会等待您的expect
调用运行,并且会过早地认为测试成功。
来自 Mocha's docs :
Simply invoke the callback when your test is complete. By adding a callback (usually named done) to it(), Mocha will know that it should wait for this function to be called to complete the test.
关于JavaScript+ Mocha + Chai 。为什么我的测试总是通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46456118/