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:预期的undefined深度相等” 在Context.it(test \ q1_pyramid_of_stars.spec.js:24:44)
答案 0 :(得分:2)
您的代码正常运行,您的测试也正常运行。这里的问题是您的buildPyramid
函数总是返回未定义,因为您只是在使用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;
};