[英]How to check if object is promise in Angular unit tests?
I want to have an assert that checks if the returned object from calling a method is a promise. 我想有一个断言,检查从调用方法返回的对象是否为Promise。
Is it enough to check if it exists and has a then
method? 检查它是否存在并具有then
方法是否足够?
Or is there a better way of doing this since having a then
method doesn't guarantee the object is a $q
deferred promise? 还是有更好的方法来执行此操作,因为使用then
方法不能保证对象是$q
递延的诺言?
EDIT: 编辑:
The question is not duplicate of " Any way to know if a variable is an angularjs promise? ". 问题不是“ 任何方法都知道变量是否是angularjs promise? ” 的重复 。
The solution for that question is to ensure that a promise is returned using $q.when()
. 该问题的解决方案是确保使用$q.when()
返回承诺。
I'm asking how to know that an object is a promise, not how to make it one if it isn't. 我在问如何知道一个对象是一个承诺,而不是如何使它成为一个承诺。
Thanks. 谢谢。
As far as I can tell, there is no way to do this directly. 据我所知,没有办法直接做到这一点。 When constructing objects, i normally do it like this: 当构造对象时,我通常这样做:
function Derp(){
this.constructor = Derp;
}
Derp.prototype.method = function(){};
So that I can: 这样我可以:
expect( new Derp() instanceof Derp ).toBe(true);
but in both $q.promise and $q itself, there are no constructor or prototype properties except for the constructor property in their __proto__ (in chrome) objects; 但是在$ q.promise和$ q本身中,除了其__proto__(在chrome中)对象中的Constructor属性外,没有构造函数或原型属性; and even those just point to JavaScripts' fundamental Object. 甚至那些都指向JavaScript的基本对象。
So in order to test that something is a promise, you have to make the assumption that the object you're returning is a promise based on its' other properties: 因此,为了测试某事物是否是一个承诺,您必须基于它的其他属性,假设要返回的对象是一个承诺:
expect(typeof result.when).toBe('function');
expect(typeof result.then).toBe('function');
I don't like it either, but that's the only way I can think of to do this. 我也不喜欢,但这是我想到的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.