次のようなディレクトリ構造だとします。
package.json
bower.json
karma.conf.js
test/
fixture/
hoge.txt
unit/
HogeSpec.js
まずは karma をインストールします。
$ npm install -g karma-cli
$ npm install --save-dev karma
jasmine でフィクスチャを使うために jquery と jasmine-jquery をインストールするのですが、karma-jasmine の jasmine が 1 系なので、jasmine-jquery も 1 系にしないと動作しません。
$ bower install --save-dev jquery
$ bower install --save-dev jasmine-jquery#~1
次に karma.conf.js を作成します。
ポイントは jquery と jasmine-jquery を files に指定することと、フィクスチャを下記のように files で pattern と included を付けて指定することです。
pattern に指定するものは普通に files に指定するものと同じですが、included: false
が無いとテストの開始時にフィクスチャを JavaScript として読み込もうとしてしまいます。
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'bower_components/jquery/dist/jquery.min.js',
'bower_components/jasmine-jquery/lib/jasmine-jquery.js',
'test/unit/**/*.js',
{ pattern: 'test/fixture/**', included: false }
],
exclude: [],
preprocessors: {},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
テストコードを作成します。
describe("HogeSpec", function(){
beforeEach(function(){
jasmine.getFixtures().fixturesPath = 'base/test/fixture';
});
it("hogehoge", function(CalendarConverter){
var fixture = readFixtures('hoge.txt');
expect(fixture).toBe("hogehoge\n");
});
});
jasmine.getFixtures().fixturesPath
でフィクスチャのパスを指定するのですが、karma.conf.js の files で指定したファイルは、basePath からの相対パスの先頭に base を付けたパスで公開されます。なので、今回のケースでは test/fixture
ではなく base/test/fixture
と指定します。
あとは readFixtures でフィクスチャを読むことができます。