我已经尝试并试图让它发挥作用。 documentation充其量是简洁的:
resetExpectations(); - 重置所有请求预期,但保留所有后端定义。通常,当您想要重用 $httpBackend mock 的相同实例时,您会在多阶段测试期间调用 resetExpectations。
每次我的第二个请求被调用时,我的结果总是有第一个结果的数据。看看这个 fiddle http://jsfiddle.net/tbwn1gt0/2/我在第一次刷新后重置期望,然后设置新的期望/结果,然后再次刷新以产生不正确的数据。
// --- SPECS -------------------------
var url = '/path/to/resource';
var result = '';
describe('$httpBackend', function () {
it("expects GET different results in subsequent requests", inject(function ($http, $httpBackend) {
successCallback = function(data){
result = data;
}
// Create expectation
$httpBackend.expectGET(url).respond(200, 'mock data');
// Call http service
$http.get(url).success(successCallback);
// flush response
$httpBackend.flush();
console.log( result ); // logs 'mock data'
// Verify expectations
expect( result ).toContain('mock data'); // works as it should
// reset the expectations
$httpBackend.resetExpectations();
// set the fake data AGAIN
$httpBackend.expectGET(url).respond(200, 'doof the magic cragwagon');
// get the service AGAIN
$http.get(url).success(successCallback);
expect( result ).toContain('doof'); // does not work, result is original result
console.log( result ); // logs 'mock data'
}));
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
我尝试过的其他事情包括添加一个带有 resetExpectations 的 afterEach(将每个请求放在一个新的 it 语句中)。以及一系列其他随机尝试。如果它试图将预期的 url 更改为非预期的内容,它就会出错——所以我知道请求至少是通过 httpBackend 处理的。
这是缺陷还是我实现不当?
最佳答案
.resetExpectations()
确实按预期工作,但您只是忘记刷新第二个 http 请求。
// set the fake data AGAIN
$httpBackend.expectGET(url).respond(200, 'doof the magic cragwagon');
// get the service AGAIN
$http.get(url).success(successCallback);
$httpBackend.flush(); // flush the second http request here
expect( result ).toContain('doof'); // does not work, result is original result
console.log( result ); // logs 'mock data'
JSFiddle 示例: http://jsfiddle.net/4aw0twjf/
附言。实际上,$httpBackend.resetExpectations()
对于您的测试用例不是必需的。
关于javascript - 如何实际重置 $httpBackend 期望值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25370273/