gpt4 book ai didi

javascript - Jasmine 测试对象在 Ajax 方法 spy 调用上的状态

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:44:39 25 4
gpt4 key购买 nike

我正在对使用 Rails Resource 的 Angular Controller 进行单元测试处理从 Rails 应用程序获取和发布模型数据的工厂。 POST 是通过模型上的方法完成的,例如(使用模型 $scope.resource):

$scope.resource.update().then(successHandler, failureHandler);

我有一个监视此方法的方法来阻止 Ajax 调用,因此我可以对 Controller 进行单元测试:

resUpdateSpy = spyOn($scope.resource, 'update').and.callFake(function() { 
return {then: function(success, failure){ success(resUpdateResponse); }};
});

在我的 Controller 方法之一中,我希望资源与某些数据(特别是 strip 数据)一起发布。数据将在相同方法的 POST 之后被覆盖,所以我无法在之后测试模型的状态。理想情况下,我想要这样的东西:

expect($scope.resource.update).toHaveBeenCalled().whileValueOf($scope.resource.stripeKey).isEqualTo('tok123');

显然,这种方法在 vanilla Jasmine 中不存在。 Jasmine 中是否有一种方法( Vanilla 或通过第三方项目)在调用给定 spy 时测试值的状态?还是有另一种方法来测试我缺少的这种情况——具体来说,模型在其数据 POST 之前的状态?

我在 Angular 1.3.14 应用程序上运行 Jasmine 2.2.0 和 Teaspoon 1.0.2。

最佳答案

您可以添加自己的 jasime 匹配器,您需要的是

jasmine.Matchers.prototype.toBeResolvedWith = function() {
var done, expectedArgs;
expectedArgs = jasmine.util.argsToArray(arguments);
if (!this.actual.done) {
throw new Error('Expected a promise, but got ' + jasmine.pp(this.actual) + '.');
}
done = jasmine.createSpy('done');
this.actual.done(done);
this.message = function() {
if (done.callCount === 0) {
return ["Expected spy " + done.identity + " to have been resolved with " + jasmine.pp(expectedArgs) + " but it was never resolved.", "Expected spy " + done.identity + " not to have been resolved with " + jasmine.pp(expectedArgs) + " but it was."];
} else {
return ["Expected spy " + done.identity + " to have been resolved with " + jasmine.pp(expectedArgs) + " but was resolved with " + jasmine.pp(done.argsForCall), "Expected spy " + done.identity + " not to have been resolved with " + jasmine.pp(expectedArgs) + " but was resolved with " + jasmine.pp(done.argsForCall)];
}
};
return this.env.contains_(done.argsForCall, expectedArgs);
};

更多信息请点击此处 https://gist.github.com/gr2m/2191748

评论后更新:

基本上 jasmine 支持自定义匹配器。一些内置匹配器是 toBe、toEqual 等。您可以添加自己的 custom matcher检查 promise 。

var customMatchers = {

toHaveBeenResolved: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
var result = {};
// do you comparison logic here
result.pass = true/false;
result.message = 'some message about test result';
return result;
}
}

this.actual 是一个 promise ,你可以像这样解决它

result = {};
promise.then(function(value){
result.value = value;
result.status = 'Resolved';
}, function(value){
result.value = value;
result.status = 'Rejected';
});

一旦您声明了您的自定义匹配器,请在 beforeEach 回调的测试用例中使用它。

beforeEach(function() {
jasmine.addMatchers(customMatchers);
});

关于javascript - Jasmine 测试对象在 Ajax 方法 spy 调用上的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31615949/

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