레이블이 jasmine인 게시물을 표시합니다. 모든 게시물 표시
레이블이 jasmine인 게시물을 표시합니다. 모든 게시물 표시

2015년 8월 25일 화요일

Write javascript test case with Jasmine

Jasmine is one of the javascript test-framework. As described in official introduction documents, It is a  "Behavior-Driven JavaScript Test Framework" and it provides many useful API to write test case easily. If you have a experience about junit in java world, you can easily learn it.

Whenever I learn new programming language, I have been trying to learn its unit-test framework first. It is a quite useful. By writing learning test case from the very beginning of learning, you can easily learn how to test it with basic knowledge of your programming language. In most of cases, the code that easy to test is more easy to maintain. Well-made test cases can be a specification of user's requirements. It is more useful than well-made document. As application is going forward, it can be guard to protect legacy functionality.  


1.Write test case

Jasmine test have a following structure. You can define test suite with "describe" method. It can have many test cases. Each of test case is defined by "it" method. The first argument of "it" method like [line 2], It is a description of test case. The second argument is a function which is called when this test case is executed. The expected result of logic or expected return value of function can be defined in "expect" method. With "toBe" method, you can call actual logic or function which you want to test. Not only "toBe", but Jasmine also provides many useful Matcher and API. You can find details in API documents


2. Execute test case

Then, How can we execute test case? You need to download Jasmine from release page. There is a zip file. In there, you can find "SpecRunner.html". As see in [line 15], it includes source files which contains some logic. [line 18] includes test case file which contains test case to test logic or function in source files.

If open "SpecRunner.html" with web browser, you can see the followings,


























3. Tools

Debugging and checking console logs are very routine work when we do programming. Chrome and Firefox provides very convenient tools for this. Below is developer tool of Chrome browser.











My mother language is not english. Please understand my poor english. :D 

2015년 8월 1일 토요일

자바스크립트 테스트 프레임워크 - 자스민 ( Jasmine )

자스민은  자바스크립트을 테스트하기 위한 테스트 프레임워크이다. 소개 문서에서 설명하듯이 Behavior-Driven JavaScript 으로, 테스트 케이스를 쉽게 작성할 수 있게 api 가 구성되어 있다. 자바에서의 junit 과 같은 테스트 프레임워크를 사용해본 경험이 있다면 쉽게 익힐 수 있다.

나는 새로운 언어나 기술을 익힐 때, 그 기술의 테스트 프레임워크부터 익혀서 사용하려고 노력하고 있다. 이것은 여러모로 도움이 된다. 배움의 초반에서부터 학습테스트(learning test) 을 써 봄으로서, 기술에 대한 기본적인 내용과 함께 테스트 케이스를 어떻게 써야 하는지도 알게 된다. 대개의 경우 테스트 하기 쉬운 코드가 변경이나 유지보수 하기도 편하다. 또한 어느 정도 기술을 익히고, 실무에 도입할 때에도 테스트 케이스를 이용해 점진적으로 개선해 나갈 수 있다. 동료들과 지식 공유에도 유용하다. 개인적으로 잘 만들어 둔 테스트 케이스는 그 소프트웨어의 명세(specification)가 된다고 생각한다. 이것은 그 어떤 문서보다 유용하다. 또한, 소프트웨어가 계속 발전해가는 과정에서 새로운 기능의 변경들이 기본 기능들의 깨트리지 않는지  지킴이 역활도 수행한다.

1.테스트 작성
자스민의 테스트는 아래와 같은 구조로 되어 있다.
"describe" 을 통해서 test suite을 정의한다. 이것은 여러개의 test case을 가지고 있다. 각가의 test case는 "it"을 통해서 정의한다. [라인 2]에서와 같이 첫번째 인자는 그 테스트 케이스에 대한 설명이 된다. 두번째 인자는 함수로 실제로 해당 테스트 케이스가 실행될 때 이 함수가 호출된다. "expect"  실제 함수 호출의 결과 값이나 로직이 실행되는 결과값을 가지게 하고, "toBe" 을 통해서 그 로직의 기대되는 값을 기술한다. 자스민에서는 테스트를 위한 여러 Matcher 및 API을 지원하고 있다. 이에 대한 자세한 내용은 API  문서를 참조하자.
2. 테스트 실행
그렇다면 테스트 케이스의 실행은 어떻게 해야 하는가? 먼저 자스민 릴리즈 페이지에서 자스민을 다운로드 하자. 압축을 풀어서 보면 SpecRunner.html 이 포함되어 있는 것을 알 수 있다.
[라인 15]에서는 실제 로직을, [라인 18]에서는 테스트 케이스 파일을 포함하고 있다.

그리고 이것을 브라우저를 통해서 열게 되면 아래와 같은 화면을 볼 수 있다.


























3. 도구
개발이나 테스트 케이스를 작성하면서 디버그나 콘솔 로그확인등은 매우 일상적인 작업이다. 이때 크롬이나 파이어폭스 브라우저의 개발자 도구를 이용하면 매우 편하다.



2015년 7월 26일 일요일

자바스크립트의 타입과 문법


자바스크립트의 기본적인 타입과 문법에 대해서 간단하게 살펴본다. 이 글을 읽는 독자는 기본적으로 프로그래밍 언어에 대한 경험이 있다고 가정하고 모든 내용을 자세하게 설명하지는 않는다. 자바스크립트만의 특이할만한 사항을 위주로 살펴본다. 학습테스트는 자바스크립트 테스트 프레임워크인 자스민을 이용해서 작성되었다. 자스민에 대한 사용법은 이 전에 작성했던 "자스민 사용법" 글을 참조하자.
  1. 자바스크립트는 동적 타입언어입니다.
    변수를 선언할 때 별다른 타입을 명시할 필요가 없고, 타입은 실행시간에 자동으로 변환이 됩니다. 아래의 예제에서는 변수를 선언할 때는 "var" 라는 키워드을 사용하였을 뿐, 특별한 타입을 명시하지 않았습니다. 또한 별다른 타입변환 없이 연산이 가능합니다.(물론 사용할때는 주의를 기울여야 합니다.)
  2. 변수
    "var" 키워드를 사용하지 않으면, global 변수를 의미합니다. 아래 예제에서 9 라인과 13 라인을 유심히 살펴보시기 바랍니다.
  3. undefined, null
    변수를 선언하고 아무값도 할당하지 않는 경우 "undefined" 으로 취급됩니다. 하지만 문맥에 따라 undefined 과 null 이 동적으로 변환이 이루어짐을 알 수 있습니다. "undefined" 은 숫자연산구문에서 NaN(Not a Number)으로 취급됩니다. 하지만 "null" 의 경우는 0으로 취급됩니다.
  4. constant
    constant 로 선언된 이름은 변수나 함수이름으로 다시 선언될 수 없습니다. MDN 문서에서는 constant 로 선언된 경우 값을 재할당하는 것도 안 된다고 했으나 테스트 해보니 잘 되었습니다. :-P
  5. array
    일반적인 프로그래밍 언어의 array 와 유사합니다. 라인 6와 같이 값이 없는 경우 undefined 로 취급됩니다. 
  6. object
    오브젝트의 선언과 오브젝트의 멤버들에 접근하는 방법을 유심히 살펴봐야 합니다. 라인 9 에서와 같이 멤버 이름(Key)을 숫자로 사용한 경우 배열과 같이 접근할 수 도 있습니다. 하지만 이름이 숫자가 아닌경우, 라인 4에서 사용한 방식이나 라인 6에서와 같은 방식으로 접근해야 합니다. 라인 8과 같은 경우는 사용할 수 없습니다. 자바스크립트 에러를 발생시키게 됩니다.
  7. 참고
    - MDN - https://developer.mozilla.org/en/docs/Web/JavaScript
    - Jasmine - http://jasmine.github.io/2.3/introduction.html



2015년 7월 4일 토요일

angularjs unittest

0. prepare project for unitest
We need angular-mocks.js. You can download it from http://angularjs.org and https://code.angularjs.org/1.4.1/. I recommend to read the post before following this post if you are not familiar with angularjs and nodejs.

$ tree angularjs-unittest/
|____
| |____angular-animate.js
| |____angular-mocks.js
| |____angular-route.js
| |____angular-sanitize.js
| |____angular-touch.js
| |____angular.js
| |____bootstrap-theme.css
| |____bootstrap.css

1. configure Karma test-runner
You should configure karma per each project respectively . You can see the following questions.
$ karma init karma.config.js

karma.config.js is created.
|____angular-animate.js
|____angular-mocks.js
|____angular-route.js
|____angular-sanitize.js
|____angular-touch.js
|____angular.js
|____bootstrap-theme.css
|____bootstrap.css
|____karma.config.js

2. create unit test file in tests
|____angular-animate.js
|____angular-mocks.js
|____angular-route.js
|____angular-sanitize.js
|____angular-touch.js
|____angular.js
|____bootstrap-theme.css
|____bootstrap.css
|____karma.config.js
|____tests
| |____hellotest.js

3. start karma
$ karma start karma.config.js








We used jasmine testing framework. You may noticed that second test case is failed. Whenever you make changes, Karma automatically detect changes and run all unit test.