【问题标题】:JavaScript+Mocha+Chai. Why do my test always pass?JavaScript+摩卡+柴。为什么我的测试总是通过?
【发布时间】:2017-09-27 19:48:42
【问题描述】:

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

【问题讨论】:

    标签: javascript mocha.js chai


    【解决方案1】:

    您需要将done 声明为it 的参数。

    it('Does x', (done) => {
      someAsyncFunc((err, result) => {
        done()
      })
    })
    

    通过声明第一个参数,您实际上是告诉 mocha 等到 done 被调用,否则它只是认为它是一个同步测试

    因此,它不会等待您的 expect 调用运行,并且会过早地认为测试成功。

    来自Mocha's docs

    只需在测试完成时调用回调。通过向 it() 添加一个回调(通常命名为 done),Mocha 将知道它应该等待调用此函数以完成测试。

    【讨论】:

    • 啊.. 非常感谢!现在它就像一个魅力! + 我还发现应该有 'getElement_s_ByTagName' :)
    【解决方案2】:

    应该是:

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

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多