在摩卡测试中,500等于400次通过?

时间:2016-07-25 06:10:48

标签: node.js mocha chai

为什么以下测试通过?

"use strict";

const
    path = require('path'),
    Dexter = require('../src/Dexter.js'),
    chai = require('chai'),
    chaiHttp = require('chai-http'),
    expect = chai.expect,
    dexterServer = new Dexter(path.resolve(__dirname, 'test/data/sample.har'));

chai.use(chaiHttp);
describe('Rest API', () => {
    before(() => {
        dexterServer.startUp();
    });

    it('should\'ve started the server', function () {
        chai.request('http://127.0.0.1:1121')
            .get('/')
            .end(function(err, response){
                console.log(response.status);
                expect(500).to.equal(400);// This passes? What?
                done();
            });
    });

    after(() => {
        dexterServer.tearDown();
    });
});

当我执行response.status的console.log时,我看到了200.但是当我这样做时

expect(response.status).to.equal(400);//response.status is an int

通过测试!

我做错了什么?

3 个答案:

答案 0 :(得分:1)

你忘了传递完成的回调。 it被视为同步,有0个假设。

it('should\'ve started the server', function (done) {
    chai.request('http://127.0.0.1:1121')
        .get('/')
        .end(function(err, response){
            console.log(response.status);
            expect(500).to.equal(400);// This passes? What?
            done();
        });
});

答案 1 :(得分:0)

您必须在doneitbefore语句中传递after以维持异步流程。

describe('Rest API', (done) => {
before(() => {
    dexterServer.startUp();
});

it('should\'ve started the server', function (done) {
    chai.request('http://127.0.0.1:1121')
        .get('/')
        .end(function(err, response){
            console.log(response.status);
            expect(500).to.equal(400);// This passes? What?
            done();
        });
});

after((done) => {
    dexterServer.tearDown();
});
});

答案 2 :(得分:0)

Mocha支持承诺,因此您可以使用chai-http产生承诺并返回承诺的事实:

it('should\'ve started the server', function () {
    // Return the promise.
    return chai.request('http://127.0.0.1:1121')
        .get('/')
        // Use .then instead of .end.
        .then(function(response){
            console.log(response.status);
            expect(500).to.equal(400);
        });
});

如果您需要对错误进行特殊处理,您也可以拥有.catch。否则,您可以让Mocha将任何错误视为失败。