Jasmine的spyOn()是否允许执行spi on函数? [英] Does Jasmine's spyOn() allow the spied on function to be executed?

查看:83
本文介绍了Jasmine的spyOn()是否允许执行spi on函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jasmine的spyOn()方法是否允许执行spied函数,或者执行-在调用(即将获得)spied方法时拦截调用,并返回true.

Does Jasmine's spyOn() method allow the spied on function to be executed, or does it, kind of - intercept the invocation when the spied method is (about to get) invoked, and returns true.

PS:有人能指出我对spyOn()内部运作的解释吗?

PS: Could anyone point me to the explanation of spyOn()'s inner workings?

推荐答案

间谍:

间谍可以伪装成函数或对象,可以在编写单元测试代码以检查函数/对象的行为时使用

var Person = function() {};
Dictionary.prototype.FirstName = function() {
return "My FirstName";
};
Dictionary.prototype.LastName = function() {
return "My LastName";
};
Person.prototype.MyName = function() {
return FirstName() + " " + LastName();
};

Person.prototype.MyLocation = function() {
Return "some location";
};

describe("Person", function() {
    it('uses First Name and Last Name for MyName', function() {
        var person = new Person;
        spyOn(person , "FirstName"); 
        spyOn(person, "LastName"); 
        person.MyName();
        expect(person.FirstName).toHaveBeenCalled(); 
        expect(person.LastName).toHaveBeenCalled(); 
    });
});

通过SpyOn,您可以知道是否已调用某些功能/尚未调用

expect(person. MyLocation).not.toHaveBeenCalled();

您可以确保间谍始终返回给定值并对其进行测试

spyOn(person, " MyName ").andReturn("My FirstNameMy LasttName ");
var result = person.MyName();
expect(result).toEqual("My FirstName  My LasttName ");

间谍可以调用伪造函数

it("can call a fake function", function() {
var fakeFun = function() {
alert("I am a spy!");
return "hello";
};
var person = new person();
spyOn(person, "MyName").andCallFake(fakeFun);
person. MyName (); // alert
})

您甚至可以创建一个新的间谍函数或对象并加以利用

it("can have a spy function", function() {
var person = new Person();
person.StreetAddress = jasmine.createSpy("Some Address");
person. StreetAddress ();
expect(person. StreetAddress).toHaveBeenCalled();
});

这篇关于Jasmine的spyOn()是否允许执行spi on函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆