javascript - 为什么我的 Javascript 代码没有通过 chai 中的单元测试用例

标签 javascript unit-testing mocha.js chai

java脚本中星形代码金字塔失败的测试用例

我的输出与用 Mocha 编写的测试用例不匹配。可能是\n 字符有问题。

const buildPyramid = (num) => {
  var stars = '';
  for (var i = 1; i <= num; i++) {
    for (var k = 1; k <= num - i + 1; k++) {
      stars += ' ';
    }
    for (var j = 1; j <= i; j++) {
      stars += '* ';
    }
    console.log(stars + '\n');
    stars = '';
  }


};

我的测试用例:

const chai = require('chai');
const expect = chai.expect;
const pyramid = require('../solutions/q1_pyramid_of_stars.js');

describe('Testing - pyramid_of_stars', () => {
  it('module return type test case', (done) => {
    expect(typeof pyramid).to.deep.equal('function');
    done();
  });

  it('positive test case for odd count of height', (done) => {
    expect(pyramid(5)).equal(
      '     *  \n    * *  \n   * * *  \n  * * * *  \n * * * * *  \n');
    done();
  });

  it('positive test case for even count of height', (done) => {
    expect(pyramid(6)).equal(
      '      *  \n     * *  \n    * * *  \n   * * * *  \n  * * * * *  \n * * * * * *  \n');
    done();
  });

  it('negative test case', (done) => {
    expect(pyramid('invalid value')).to.deep.equal('');
    done();
  });
});

错误:1) 测试 - pyramid_of_stars 奇数高度的正测试用例: AssertionError: 预期未定义等于 ' *\n * *\n * * *\n * * * *\n * * * * *\n' 在 Context.it (test\q1_pyramid_of_stars.spec.js:12:22)

2) 测试 - pyramid_of_stars 偶数高度的正面测试用例: AssertionError:预期未定义等于' *\n * *\n * * *\n * * * *\n * * * * *\n * * * * * *\n' 在 Context.it (test\q1_pyramid_of_stars.spec.js:18:22)

3) 测试 - pyramid_of_stars 负测试用例: AssertionError:预期未定义深度等于'' 在 Context.it (test\q1_pyramid_of_stars.spec.js:24:44)

最佳答案

您的代码工作正常,您的测试也是如此。这里的问题是您的 buildPyramid 函数总是返回 undefined 因为您只是使用 console.log 来输出结果。

试着把它改成这样

const buildPyramid = num => {
  var stars = '';
  for (var i = 1; i <= num; i++) {
    for (var k = 1; k <= num - i + 1; k++) {
      stars += ' ';
    }
    for (var j = 1; j <= i; j++) {
      stars += '* ';
    }
    stars = stars + '\n';
  }
  return stars;
};

关于javascript - 为什么我的 Javascript 代码没有通过 chai 中的单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57514801/

相关文章:

javascript - 以非名称的形式验证 radio 元素

python - 使用 Python unittest 测试回调调用的正确方法是什么?

c++ - 对不适合作为新类提取的私有(private)方法进行单元测试的好方法是什么?

c# - 如何让 VS 忽略 Test dll 的代码覆盖率

javascript - 如何在hook之前在mocha中多次调用(NPM)请求?

node.js - Mocha 断言失败导致超时

javascript - 如何在 ag-grid 的事件方法中使用 javascript 默认事件对象

javascript - CSS布局问题、流程图设计

javascript - Mocha 和 Chai 未能兑现 promise

javascript - 包含带索引的多次求和的 MathJax 方程