用Jasmine/Angular测试async函数
Test async function with Jasmine/Angular
有以下Angular代码:
$scope.clickByPoint = function(marker, eventName, point) {
var geocoder, location;
$scope.options.info.point = point;
$scope.options.info.show = true;
$scope.searched = false;
$scope.address = "";
geocoder = new google.maps.Geocoder();
location = {
lat: parseFloat(point.latitude),
lng: parseFloat(point.longitude)
};
geocoder.geocode({location: location}, function(results, status) {
$scope.searched = true;
if (status === google.maps.GeocoderStatus.OK) {
$scope.address = results[0].formatted_address;
}
$scope.$digest();
});
};
和我的茉莉测试:
describe('$scope.clickByPoint', function() {
var point;
beforeEach(inject(function(_Point_) {
point = _Point_.build('PointName', { latitude: 0, longitude: 0 });
}));
describe('try to find the address', function() {
it('initialize google maps info window', function() {
$scope.clickByPoint(null, null, point)
expect($scope.searched).toEqual(true);
});
})
});
正如你所看到的,我正在尝试测试'scope。搜索'变量被改变,但它总是'假',因为函数是异步的。我怎样才能正确地测试这段代码?
-
在这种情况下,在测试中使用Google .maps. geocoder()的模拟,使用jasmine,因为您正在测试clickByPoint()逻辑,而不是Google maps api。
var geocoder = new google.maps.Geocoder(); jasmine.createSpy("geocode() geocoder").andCallFake(function(location, callback) { // no wait time ... var results = {fake:'', data:''}; var status = google.maps.GeocoderStatus.OK; // get OK value and set it OR redefine it with a Spy. callback(result, status); });
-
现在你可以使用你的测试:
describe('try to find the address', function() { it('initialize google maps info window', function() { $scope.clickByPoint(null, null, point); expect($scope.searched).toEqual(true); }); })
相关文章:
- jQuery加载的async和ready函数不工作
- 什么'这是从第三个函数上的async 1st函数获得结果的更好方法
- Node.js使用async函数返回的对象
- 对async函数进行同步调用
- 如何使我的async函数在angular中成为一个承诺
- 如何在$scope对象中设置一个async函数之外的变量
- async函数中的可选参数
- 有没有可能在没有return关键字的情况下解析async函数?
- 终止ecmascript7 async函数
- 用Jasmine/Angular测试async函数
- 等待async函数结束
- 编译typescript而不编译async函数
- 多次调用Async函数
- 在其中调用async函数
- 为什么bluebird promise内部的async函数抛出的错误没有被.catch()函数捕获?
- Javascript: Async嵌套函数在其他Async函数中会产生意想不到的结果
- 调用QUnit's断言.多次Async函数
- 让Jasmine等待Async函数完成
- 从Javascript中的async函数获取返回值
- 如何在marrionete.js中构建一个调用链来渲染itemView,并在itemView中使用async函数延迟