Karma + Jasmine + JSONFixtures:无法读取属性' ajax'未定义的

时间:2016-01-02 05:39:20

标签: javascript angularjs jasmine karma-runner karma-jasmine

背景

我正在尝试为我的javascript jsonTransformer编写单元测试,它将JSON-Schema转换为项目特定的JSON。

作为第一个测试,我希望对此转换器进行黑盒测试,该测试接收输入-JSON并将转换后的JSON与正确的JSON进行比较。

我使用Karma和Jasmine作为测试环境。

问题:

如何解决以下错误?

TypeError: Cannot read property 'ajax' of undefined
at jasmine.JSONFixtures.loadFixtureIntoCache_ (.../node_modules/jasmine-jquery/lib/jasmine-jquery.js:257:6)
at jasmine.JSONFixtures.getFixtureData_ (.../node_modules/jasmine-jquery/lib/jasmine-jquery.js:249:41)
at jasmine.JSONFixtures.read (.../node_modules/jasmine-jquery/lib/jasmine-jquery.js:238:12)
at jasmine.JSONFixtures.proxyCallTo_ (.../node_modules/jasmine-jquery/lib/jasmine-jquery.js:272:29)
at window.getJSONFixture (.../node_modules/jasmine-jquery/lib/jasmine-jquery.js:836:38)
at Object.<anonymous> (...test/test.js:24:8)
at Object.e [as invoke] (.../node_modules/angular/angular.min.js:39:394)
at Object.workFn (.../node_modules/angular-mocks/angular-mocks.js:2439:20)

结构:

所有依赖项都在&#34; ./ node-modules /&#34;。中 karma.config位于&#34; ./ node-modules / karma /&#34;。

index.html位于&#34; ./ app /&#34;。
JS文件位于&#34; ./ app / js /&#34;。

test.js位于&#34; ./ test /&#34;。
JSON模拟位于&#34; ./ test / mock /&#34;。

代码:

karma.config:

basePath: '../..',

frameworks: ['jasmine'],

files: [
    'node_modules/jasmine-jquery/lib/jasmine-jquery.js',
    'node_modules/angular/angular.min.js',
    'node_modules/angular-mocks/angular-mocks.js',
    'app/js/formulargenerator.js',
    'app/js/*.js',
    'test/*.js',

    // fixtures
    {pattern: 'test/mock/*.json', watched: true, served: true, included: false}
],

test.js:

&#13;
&#13;
describe('jsonTransformer', function() {
	var $httpBackend, scope;

	beforeEach(inject(function ($injector, $rootScope, $controller) {
    	jasmine.getJSONFixtures().fixturesPath='base/test/mock';

		dump(jasmine.getJSONFixtures());
		dump(getJSONFixture('mock_formularSpecification.json'));

		$httpBackend = $injector.get('$httpBackend');
    	$httpBackend.whenGET('http://localhost:8080/myProject/rest/form/1').respond(
        	getJSONFixture('mock_input.json')
    	);

    	scope = $rootScope.$new();
    	$controller('jsonTransformer', {'$scope': scope});
    	dump($controller);
	}));

	var transformedJSON = getJSONFixture('mock_output.json'); //todo: transform

	it('should have transformed the input-JSON to the correct output-JSON', function() {
		$httpBackend.flush();
    	expect(transformedJSON).toBe(getJSONFixture('mock_angularFormly.json'));
	});

});
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

感谢Chanthu指出我遗漏的依赖:jquery

我通过npm安装了jquery,但我忘了将它列在karma.conf文件中:&#39; node_modules / jquery / dist / jquery.min.js&#39;,