3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

npmとJasmineでテスト環境を整える

Last updated at Posted at 2019-09-12

Jasmineの公式URLをたどってのインストールが手間なため、npmを使ってコマンドラインで簡単にインストールする手順をまとめました。

(1/5)環境 + ツール

  • Windows
  • Windows PowerShell
    → Git Bash でもOK
  • node.js
  • Jasmine

※node.jsはすでにインストールされているものとします。

(2/5)Jasmine をインストール

npm公式:jasmine - npm

まずはWindows PowerShellを起動。
プロジェクトのルートディレクトリ( C:\Users\●●●●●\project )に移動し、npm を使って Jasmine をインストール。

C:\Users\●●●●●\project> npm install --save-dev jasmine

yarn がインストールされている場合は yarn install jasmine → yarn add jasmine でも可能。
処理が完了すると、ルートディレクトリ内に以下のファイルとディレクトリが作成されます。
参考:
yarn install | Yarn
jasmine | Yarn - Package Manager

node_modules
package-lock.json

(3/5)Jasmine の準備

次に先ほどインストールした Jasmine を用いて、プロジェクト内で Jasmine を使う準備をします。
以下のコマンドを実行してください。

C:\Users\●●●●●\project> node_modules/.bin/jasmine init

すると、ルートディレクトリ内に spec ディレクトリが追加されます。

node_modules
spec
┗ support
   ┗ jasmine.json
package-lock.json

テスト対象となる js ファイルや、テスト処理を書き込んだ js ファイルは spec ディレクトリ直下に配置します。

(4/5)テストコードを書く

Jasmine を使った単体テストには以下の2つのファイルが必要です。

  • テスト対象となる js ファイル
  • テスト処理を書き込んだ js ファイル

以降、両者のサンプルを作成していきます。

helloWorld.js (テスト対象となる js ファイル)

helloWorld.js
var helloWorld = function() {
  return 'Hello, World!';
}

module.exports = helloWorld;

helloWorld_spec.js (テスト処理を書き込んだ js ファイル)

helloWorld_spec.js
var helloWorld = require('./helloWorld');

describe('Hello World', function() {
  it('says hello world', function() {
    expect(helloWorld()).toEqual('Hello, World!');
  });
});

上記2つのファイルを作成した後のディレクトリ構成は以下。

node_modules
spec
┣ support
┃ ┗ jasmine.json
┣ helloWorld.js (追加)
┗ helloWorld_spec.js (追加)
paclage-lock.json

(5/5)テスト実行

以下コマンドでテストを実行します。

C:\Users\●●●●●\project\spec> ../node_modules/.bin/jasmine helloWorld_spec.js

実行後、コードに間違いがなければ以下が表示されます。

Randomized with seed ○○○○○
Started
.


1 spec, 0 failures
Finished in 0.026 seconds
Randomized with seed ○○○○○ (jasmine --random=true --seed=○○○○○)

これで「npmでJasmineをインストールした後テスト環境を整えるまで」の手順は完了です。

参考

こちらの記事を参考にさせていただきました。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?