gpt4 book ai didi

angularjs - $http后端 : Angular Unit-Testing that a GET request is sent

转载 作者:行者123 更新时间:2023-12-04 00:08:57 25 4
gpt4 key购买 nike

我想测试(组件的) Controller 是否正在向某个 URL 发送 GET 请求(不关心响应)。我期待着

httpBackend.expectGET('/some/random/url');

会监视 http 后端,如果没有收到 GET 请求就会失败,所以我预计以下规范会失败:

describe('myApp', function() {
var httpBackend;

beforeEach(module('myApp'));

beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend;
}));

it('sends a GET request to /some/random/url', function() {
httpBackend.expectGET('/some/random/url');
httpBackend.expect('GET', '/some/random/url');
});

});

但这似乎平凡地过去了

Starting the Teaspoon server...
Teaspoon running default suite at http://127.0.0.1:56255/teaspoon/default
..

Finished in 0.01200 seconds
2 examples, 0 failures

用这个:

angular.module('myApp', []);

所以我想我误解了 expectGET 正在做什么,这不是检查我要检查的内容的方法。

最佳答案

我通常将以下代码添加到任何处理 http mocking 的规范(测试)文件中。这确保调用被刷新并且没有未完成的期望/请求。

afterEach(() => {
try {
$httpBackend.flush();
} catch (e) {
}
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});

这会像这样改变你的代码

describe('myApp', function() {
var httpBackend;

beforeEach(module('myApp'));

beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend;
}));

afterEach(() => {
try {
httpBackend.flush();
} catch (e) { // entering here is a sign your unit test failed
}
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});

it('sends a GET request to /some/random/url', function() {
httpBackend.expectGET('/some/random/url');
httpBackend.expect('GET', '/some/random/url');
});

});

关于angularjs - $http后端 : Angular Unit-Testing that a GET request is sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36433763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com