angularjs - AngularJS,Karma:无法获得 indexedDB 包装器的承诺解决工作
问题描述
我正在使用localforage并有一个 angularjs 包装器来获取项目并给出一个承诺对象
工厂.js
service.prototype.getItem = function getItem(key) {
var deferred = $q.defer();
localforage.getItem(key).then(function (item) {
//some calculations
deferred.resolve(item);
}
return deferred.promise;
}
工厂.spec.js
it('should get item', function (done) {
mocks.inject(function ($rootScope, $httpBackend, service) {
service.getItem('test').then(function(item) {
expect(item).toBe('some value');
done();
});
$rootScope.$digest();
});
}
在上面的代码中,服务回调被正确触发并获取值。但无法在 spec.js 中触发回调
解决方案
找不到你处理的地方localforage
?我想测试的目的是检查一些重要的计算,那么你应该这样做
it('should get item', function () {
spyOn(localforage, 'getItem').and.returnValue($q.resolve(item));
service.getItem('test').then(function(responseAfterCalculations) {
expect(responseAfterCalculations).toBe('some value');
});
$rootScope.$digest();
}
基本上,方法在 repo 中localforage.getItem
有自己的测试。在单元测试中,您只需测试自己的功能和 3rd 方服务实现。所以这里最好的方法是简单地模拟localforage
. 如果您想要更完整的测试,您需要一种 e2e 方法,例如基于量角器。
推荐阅读
- python - 我需要用python从一个减去另一个的范围数字中得到结果
- azure - Azure Key Vault 配置 - 间歇性“未经授权”响应
- php - Gravity Forms 中的函数以读取是否选中了复选框?
- r - 为什么我在使用 R 中的非线性回归的 plinear 算法时出现错误?
- android - WorkManager doWork 被解雇两次
- sql-server - 从原始数据库创建带有百分位数的表
- sql - OPENJSON - 修改语句以忽略字符串的第一部分
- regex - 两个字符之间和多行之间的正则表达式
- ruby-on-rails - 使用 Active Storage / S3、React 和 ActiveAdmin 上传 Rails API 图像
- python - 绘制特征重要性会给出错误“数组必须都是相同的长度”