我正在尝试完成一个Jasmine测试(使用Karma和IntelliJ 13)来验证JSON文件。理想情况下,我的测试只需将JSON文件加载到数据对象中,然后让我解析以检查是否有有效的格式和数据。我不需要在之前或之后验证函数,也不需要在服务器上进行测试。
我的基本设置如下:
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结果:
http://date.jsontest.com/
而且这个很管用。
我的测试文件名为/ test /mySpec.js,而我的karma.conf.js文件位于根上。我已经将JSON文件移动到所有这些位置,没有任何进展。我做错了什么?
有答案的更新:
根据下面的答案,我将以下内容添加到我的karma.conf.js中:
// fixtures
{ pattern: 'test/*.json',
watched: true,
served: true,
included: false
}然后,我用这样的方式写我的测试:
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...然后就过去了。
发布于 2014-01-06 04:18:31
您是否通过karma.config.js为JSON文件提供服务?
您可以通过治具提供JSON文件:
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 }
],发布于 2015-01-07 23:29:50
通过夹具为JSON提供服务是最简单的,但是由于我们的设置,我们不能轻松地做到这一点,所以我编写了另一个帮助函数:
安装
bower install karma-read-json
用法
readJSON函数。示例:
var valid_respond = readJSON('json/foobar.json');发布于 2014-10-10 11:52:52
如果您正在尝试加载一个HTML文件,并且希望避免使用jasmine,您可以利用karma html2js-预处理器。
在karma.conf.js中:
// generate js files from html templates
preprocessors: {
'resources/*.html': 'ng-html2js'
},
files: [
...
'resources/*.html'
],
plugins: [
...
'karma-ng-html2js-preprocessor'
],在你的茉莉花规范中:
beforeEach(module('resources/fragment.html'));
var $templateCache;
beforeEach(inject(function (_$templateCache_) {
$templateCache = _$templateCache_;
}));
describe('some test', function () {
it('should do something', function () {
// --> load the fragment.html content from the template cache <--
var fragment = $templateCache.get('resources/fragment.html');
expect(fragment).toBe(...);
});
});https://stackoverflow.com/questions/20938320
复制相似问题