JavaScript+摩卡+柴。为什么我的测试总是通过?

JavaScript+Mocha+Chai. Why do my test always pass?

我有 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\""

它总是报告 "Passed"。

我什至可以评论 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.

应该是:

it("should say 'Hello world!'", (done) => {