問題描述
我正在嘗試完成 Jasmine 測試(使用 Karma 和 IntelliJ 13)來驗證 JSON 文件.理想情況下,我的測試將簡單地將 JSON 文件加載到數據對象中,然后讓我解析以檢查有效的格式和數據.我不需要在之前或之后驗證函數,也不需要針對服務器進行測試.
I'm trying to accomplish a Jasmine test (using Karma and IntelliJ 13) to validate JSON files. Ideally, my test would simply load a JSON file into a data object, then let me parse through to check for valid formatting and data. I don't need to validate functions before or after, nor do I need to test against a server.
我的基本設置是這樣的:
My basic setup is like this:
it("should load an external file", function(){
var asyncCallComplete, result,
_this = this;
// asyncCallComplete is set to true when the ajax call is complete
asyncCallComplete = false;
// result stores the result of the successful ajax call
result = null;
// SECTION 1 - call asynchronous function
runs(function() {
return $.ajax('/test/config.json', {
type: 'GET',
success: function(data) {
asyncCallComplete = true;
result = data;
},
error: function() {
asyncCallComplete = true;
}
});
});
// SECTION 2 - wait for the asynchronous call to complete
waitsFor(function() {
return asyncCallComplete !== false;
}, "async to complete");
// SECTION 3 - perform tests
return runs(function() {
return expect(result).not.toBeNull();
});
}
問題是無論我使用什么路徑,我都會收到 404 錯誤并且文件不會加載.我嘗試使用此測試服務從遠程服務器加載外部 JSON 結果:
The problem is that no matter what path I use, I get a 404 error and the file won't load. I've tried loading an external JSON result from a remote server using this test service:
http://date.jsontest.com/
這行得通.
我的測試文件名為/test/mySpec.js,我的 karma.conf.js 文件位于根目錄中.我已經將 JSON 文件移動到所有這些位置,但沒有運氣.我做錯了什么?
My test file is named /test/mySpec.js and my karma.conf.js file is on the root. I have moved around the JSON file to all of these locations with no luck. What am I doing wrong?
更新答案:
根據下面的答案,我將此添加到我的 karma.conf.js:
Per the answer below, I added this to my karma.conf.js:
// fixtures
{ pattern: 'test/*.json',
watched: true,
served: true,
included: false
}
然后,我這樣寫了我的測試:
Then, I wrote my test this way:
var json:any;
it("should load a fixture", function () {
jasmine.getFixtures().fixturesPath = "base/test/"
var f = readFixtures("registration.json");
json = JSON.parse(f);
expect(json).toBeDefined();
})
it("should have a title", function () {
expect(json.title).toNotBe(null);
})
etc...
它通過了.
推薦答案
您是否通過 karma.config.js 提供 JSON 文件?
Are you serving the JSON file via karma.config.js?
您可以通過夾具提供 JSON 文件:
You can serve JSON files via fixture:
files: [
// angular
'angular.min.js',
'angular-route.js',
'angular-mocks.js',
// jasmine jquery helper
'jquery-1.10.2.min.js',
'jasmine-jquery.js',
// app
'../../public/js/app.js',
// tests
'*-spec.js',
// JSON fixture
{ pattern: '/test/*.json',
watched: true,
served: true,
included: false }
],
這篇關于從 Karma/Jasmine 測試加載外部文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!