Mocha Chai Expect
by wangtn18
HTML
<link rel="stylesheet" href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css">
<script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.3.0/chai.min.js"></script>
<!-- Mocha test output goes here. -->
<div id="mocha"></div>
JavaScript
mocha.setup('bdd');
var expect = chai.expect;
function first(arr, n) {
// viết hàm first trả về giá trị đầu tiên của mảng, nếu n được truyền vào thì trả về 1 mảng chứa n giá trị đầu tiên của mảng (hoặc cả mảng nếu n lớn hơn số phần tử của mảng). Nếu n <= 0 thì trả về mảng trống.
// Tham số:
// - array: mảng gốc
// - n: số phần tử trả về
var newArr = [];
console.log(newArr)
if(n>0) {
for (var i = 0 ; i < n ; i++ ){
if(i<arr.length){
newArr.push(arr[i])
}
}
return newArr;
} else if (n < 0) {
return [] ;
} else {
var first= arr[0]
return first ;
}
}
describe('first', function () {
it('should return the first item if n is not provided', function () {
expect(first([7, 9, 0, -2])).to.equal(7);
});
it('should return an empty array if input array is empty', function() {
expect(first([], 3)).to.eql([]);
});
it('should return an array of n items if n is specified', function() {
expect(first([7, 9, 0, -2], 3)).to.eql([7, 9, 0]);
});
it('should return all items if n > array length', function() {
expect(first([7, 9, 0, -2], 6)).to.eql([7, 9, 0, -2]);
});
it('should return an empty array if n < 0', function() {
expect(first([7, 9, 0, -2], -3)).to.eql([]);
});
});
mocha.run();