除非我添加域名,即http://localhost:9808/
,否则我对$ httpBackend的茉莉花测试不会起作用由于此测试用于多个不同的环境,因此我无法使用http://localhost:9808/
如果没有域名,我会收到此错误:
未捕获错误:意外请求:获取http://localhost:9808/api/mymethod 不再需要预期
{% extends "base.html.j2" %}
{% block content %}
<form action="/test" method="POST">
{% if test_form.errors %}
{{ test_form.errors }}
{% endif %}
{{ test_form.csrf_token }}
{% for qa in test_form.question_attempts %}
<div class="well">
<div>
{{ qa.label }}
</div>
<div>
<ol type="A">
{% for subfield in qa.answer_selection %}
<li>
{{ subfield }}
{{ subfield.label }}
</li>
{% endfor %}
</ol>
{{ qa.question_id }}
</div>
</div>
{% endfor %}
{{ test_form.submitfield(class="btn btn-success") }}
</form>
{% endblock %}
我甚至尝试将这些行添加到beforeEach
//这也会引发错误
$ httpBackend.when(&#39; GET&#39;,&#39; / api / mymethod&#39;)。respond(200,mockData);
//甚至添加expect仍然会在beforeEach中抛出错误 $ httpBackend.expectGET(&#39; / API /的MyMethod&#39);
有关如何在不使用域名的情况下使其发挥作用的任何想法或建议?
以下是实际发出请求的服务代码:
describe('test my service', function () {
'use strict';
var $httpBackend,
myService;
beforeEach(inject(function (_$injector_, _$httpBackend_) {
var $injector = _$injector_;
$httpBackend = _$httpBackend_;
myService = $injector.get('myService');
// this works
//$httpBackend.whenGET('http://localhost:9808/api/mymethod').respond(200, mockData);
// this throws error
$httpBackend.whenGET('/api/mymethod').respond(200, mockData);
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('check service exists and has methods', function () {
expect(myService).toBeDefined();
expect(myService.somemethod).toBeDefined();
$httpBackend.flush();
});
});
答案 0 :(得分:0)
我猜您可以使用正则表达式来匹配网址
你可以这样做:
var method = 'GET';
var url = '/mymethod';
$httpBackend.when(method, new RegExp('\\' + url)).respond(200, mockData);
答案 1 :(得分:0)
好的,看过这篇文章https://stackoverflow.com/questions/29809436/cannot-inject-providers-into-karma-test
我可以通过将下面的beforeEach添加到我的spec文件来解决我的问题。我正在使用angular v1.5.4和angular-ui-router v0.2.18
beforeEach(module(function($urlRouterProvider) {
$urlRouterProvider.deferIntercept();
}));