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/