Javascript Koans는 KoansRunner.html을 통해 테스트를 통과하면 되는 과제인데 총 8개의 주제로 이루어져 있었다.
1. Introduction
expect 함수의 사용법 : expect(테스트 값).기대하는 조건
(기대하는 조건에 해당하는 함수 = matcher https://www.chaijs.com/api/bdd/)
it('테스트하는 값(expect의 인자)이 true인지의 여부를 검사합니다.', function () {
expect(true).to.be.true;
});
it('Matcher .equal 의 사용법을 학습합니다.', function () {
let expectedValue = 2;
expect(1 + 1).to.equal(expectedValue);
}); //.equal은 두 값이 타입까지 엄격하게 같은지 검사(strict equality, ===)한다.
2. Types-part1 : 비교연산자
비교연산자 '=='는 두 값의 일치 여부를 느슨하게 검사(loose equality)한다.
1+1이 2와 같은지 검사할 때 '=='을 사용하면 문자열인 '2'를 넣어도 오류가 나지 않는다.
따라서 모든 상황에 일일이 대응하려고 하기 보다는 엄격한 동치 연산인 '==='을 사용하는 것이 일반적이다.
3. LetConst
변수를 선언할 때 let, const, var 등을 사용할 수 있다.
그러나, var은 중복 선언이 가능해 오류가 발생할 수 있어 let, const에 비해 잘 사용하지 않는다.
let과 const의 차이는 재할당인데 코드의 가독성을 높이고 오류방지를 위해 고정값에 대해서는 const를 사용하는 것이 바람직하다.
4. Scope : 변수의 값 (변수에 담긴 값) 을 찾을 때 확인하는 곳
it('함수 선언식(declaration)과 함수 표현식(expression)의 차이를 확인합니다.', function () {
let funcExpressed = 'to be a function';
expect(typeof funcDeclared).to.equal('function');
expect(typeof funcExpressed).to.equal('string');
function funcDeclared() {
return 'this is a function declaration';
}
funcExpressed = function () {
return 'this is a function expression';
};
const funcContainer = { func: funcExpressed };
expect(funcContainer.func()).to.equal('this is a function expression');
funcContainer.func = funcDeclared;
expect(funcContainer.func()).to.equal('this is a function declaration');
});
it('lexical scope에 대해서 확인합니다.', function () {
let message = 'Outer';
function getMessage() {
return message;
}
function shadowGlobal() {
let message = 'Inner';
return message;
}
function shadowGlobal2(message) {
return message;
}
function shadowParameter(message) {
message = 'Do not use parameters like this!';
return message;
}
expect(getMessage()).to.equal(message);
expect(shadowGlobal()).to.equal('Inner');
expect(shadowGlobal2('Parameter')).to.equal('Parameter');
expect(shadowParameter('Parameter')).to.equal('Do not use parameters like this!');
expect(message).to.equal('Outer');
});
it('클로저(closure)에 대해 확인합니다.', function () {
function increaseBy(increaseByAmount) {
return function (numberToIncrease) {
return numberToIncrease + increaseByAmount;
};
}
const increaseBy3 = increaseBy(3);
const increaseBy5 = increaseBy(5);
expect(increaseBy3(10)).to.equal(13);
expect(increaseBy5(10)).to.equal(15);
expect(increaseBy(8)(6) + increaseBy(5)(9)).to.equal(28);
5. Types-part2 : 원시 자료형 vs 참조 자료형
원시 자료형은 값 자체에 대한 변경이 불가능(immutable)하지만, 새로운 값으로 재할당은 가능하다.
자바스크립트에서 원시 자료형이 아닌 모든 것은 참조 자료형이다. 참조 자료형이 원시 자료형과 다르게 작동되는 부분은 값 자체의 복사가 아니라 주소를 참조한다는 것이다. 그 이유는 참조 자료형은 immutable하지 않기 때문이다. 참조 자료형의 데이터는 동적으로 변한다.
it('원시 자료형은 값 자체에 대한 변경이 불가능(immutable)합니다.', function () {
let name = 'heesue';
expect(name).to.equal('heesue');
expect(name.toUpperCase()).to.equal('HEESUE');
expect(name).to.equal('heesue');
name = name.toUpperCase();
expect(name).to.equal('HEESUE'); // 새로운 값으로 재할당은 가능하다.
});
it('참조 자료형을 변수에 할당할 경우, 데이터의 주소가 저장됩니다.', function () {
const overTwenty = ['A', 'B', 'C'];
let allowedToDrink = overTwenty;
overTwenty.push('D');
expect(allowedToDrink).to.deep.equal(overTwenty);
overTwenty[1] = 'E';
expect(allowedToDrink[1]).to.deep.equal('E');
//.deep.equal은 배열의 요소나 객체의 속성이 서로 같은지 확인하는 matcher이다.
6. Array
Array 메서드 중 slice는 배열의 값을 복사하여 새로운 배열을 리턴한다.
it('Array 메서드 slice를 확인합니다.', function () {
const arr = ['candy', 'chocolate', 'and', 'jelly'];
//아래의 코드는 arr 전체를 복사한다. 자주 사용되니 기억해두자!
expect(arr.slice(0)).to.deep.equal(['candy', 'chocolate', 'and', 'jelly']);
});
7. Object
'this'는 method를 호출한 시점에 method를 호출한 객체를 가리킨다.
it('객체의 method를 정의하는 방법을 확인합니다.', function () {
const megalomaniac = {
mastermind: 'Brain',
henchman: 'Pinky',
getFusion: function () {
return this.henchman + this.mastermind;
},
battleCry(numOfBrains) {
return `They are ${this.henchman} and the` + ` ${this.mastermind}`.repeat(numOfBrains);
},
};
expect(megalomaniac.getFusion()).to.deep.equal('Pinky' + 'Brain');
expect(megalomaniac.battleCry(3)).to.deep.equal(`They are Pinky and the` + ` Brain`.repeat(3));
});
8. Spread Syntax (전개 구문)
객체, 배열 등을 펼쳐주는 역할로 반복 가능한 배열, 문자열 또는 이터러블에 대해서 사용이 가능하다.
함수 호출
myFunction(...iterableObj);
배열 리터럴과 문자열
[...iterableObj, '4', 'five', 6];
객체 리터럴
let objClone = { ...obj };
Rest parameter는 정해지지 않은 수(an indefinite number, 부정수) 인수를 배열로 나타낼 수 있게 한다.
function f(a, b, ...theArgs) {
// ...
}
//rest parameter는 항상 마지막 파라미터로 있어햐 한다!
'TIL 👩🏻💻' 카테고리의 다른 글
TIL : 고차함수 (0) | 2021.03.16 |
---|---|
TIL : Twittler 목업 구현하기 (0) | 2021.03.15 |
TIL : Command Line, Git (0) | 2021.03.11 |
TIL : 배열, 객체 (0) | 2021.03.09 |
TIL : Calculator (0) | 2021.03.08 |