【问题标题】:Test Cases in nodejs with mocha, chai带有 mocha、chai 的 nodejs 中的测试用例
【发布时间】:2017-09-13 07:57:34
【问题描述】:

目前,我使用mochachai 为两个函数创建了一个测试。

他们应该根据来自HTTP POST/GET请求的不同参数做出不同的响应。

但是,我想知道检查 3 个测试用例的最佳做法是什么,我希望它们具有相同的输入。

例如,

describe('Function A', function() {

it('should retrun 404 when receipt ID is invalid', function(done) {
    chai.request(server)
        .post('/generateSales/')
        .send(validParams1)
        .end(function(err, res){
            res.should.have.status(404);
            done();
        });
});

it('should retrun 404 when receipt ID is invalid', function(done) {
    chai.request(server)
        .post('/generateSales/')
        .send(validParams2)
        .end(function(err, res){
            res.should.have.status(404);
            done();
        });
});

it('should retrun 404 when receipt ID is invalid', function(done) {
    chai.request(server)
        .post('/generateSales/')
        .send(validParams3)
        .end(function(err, res){
            res.should.have.status(404);
            done();
        });
});


});

在单个 it 块中测试所有参数(validParams1,2,3)的正确方法是什么? (正如我所料他们有相同的反应)

【问题讨论】:

    标签: node.js unit-testing mocha.js chai testcase


    【解决方案1】:

    由于异步问题,您不应在 it 块内调用 for 循环。

    我找到了替代解决方案,使用 it-each 模块

    以下链接显示了当您想在 it 块中使用 20 个 API 或 20 个测试用例时,如何使用 mocha 处理异步测试循环

    https://whitfin.io/asynchronous-test-loops-with-mocha/

    【讨论】:

      【解决方案2】:

      https://mochajs.org/#dynamically-generating-tests

      describe('Function A', function() {
        let paramSets = [
          validParams1,
          validParams2,
          validParams3
        ]
        paramSets.forEach((paramSet)=>{
          // call it multiple times.
          it('should return 404 when receipt ID is invalid', function(done) {
            // this is technically a different function each time
            chai.request(server)
              .post('/generateSales/')
              .send(paramSet) // this is different for each function/test
              .end(function(err, res){
                res.should.have.status(404);
                done();
              });
          });
          // never call assert here.
          // The function passed to 'it' runs as the test.
          // The function passed to 'describe' runs first, and sets up all the tests.
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 2016-09-20
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多