【问题标题】:Mocha test with SuperTest always passes (even when wrong)使用 SuperTest 的 Mocha 测试始终通过(即使错误)
【发布时间】:2019-10-13 17:20:13
【问题描述】:

我正在使用 Mocha 和 SuperTest 来测试我的 Express API。然而,我的第一个测试似乎总是在我的.then()request() 中通过。

我将 String 传递给一个期待 Array 的测试。所以绝对应该没有通过测试。

正如预期的那样,它在then() 之外失败,但我无法访问那里的res.body 来执行我的测试。

这是我的代码:

const expect = require('chai').expect;
const request = require('supertest');

const router = require('../../routes/api/playlist.route');
const app = require('../../app');

describe('Playlist Route', function() {
    // before((done) => {

    // }
    describe('Get all playlists by user', function() {
        it('Should error out with "No playlists found" if there are no Playlists', function() {
            request(app).get('/api/playlists/all')
                .then(res => {
                    const { body } = res;

                    // Test passes if expect here
                    expect('sdfb').to.be.an('array'); 
                })
                .catch(err => {
                    console.log('err: ', err);
                });
            // Test fails if expect here
            expect('sdfb').to.be.an('array'); 
        })
    })
});

我找到了这个article,但我没有使用try catch 块,但我认为它可能与承诺有关。

【问题讨论】:

  • 它没有通过,它只是没有失败——这是有区别的。测试异步代码时必须小心,因为很容易意外编写直到测试结束之后才到达的断言(TDD 是确保不会发生这种情况的一种方法) .对于摩卡,请参阅mochajs.org/#asynchronous-code
  • 感谢您的回复。我看一下链接。

标签: node.js unit-testing mocha.js supertest mern


【解决方案1】:

快速回复

it('decription', function(done) {
    asyncFunc()
        .then(() => {
            expect(something).to.be(somethingElse)
            done()
        })
})

@jonrsharpe 评论中的详细回复

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多