工作中遇到一个问题,有一个emailValidator函数,会在前端进行email的格式检查,成功后会在后台进行 email的唯一性检查。
后台检查需要模拟API,所以找到了spyon的and.callFake方法来改写已有的API
and.callFake--spy链式添加and.callFake相当于用新的方法替换spy的方法,比如:
describe("A spy, when configured with an alternate implementation", function() {
var foo, bar, fetchedBar;
beforeEach(function() {
foo = {
setBar: function(value) {
bar = value;
},
getBar: function() {
return bar;
}
};
spyOn(foo, "getBar").and.callFake(function() {//指定callFake方法
return 1001;
});
foo.setBar(123);
fetchedBar = foo.getBar();
});
it("tracks that the spy was called", function() {
expect(foo.getBar).toHaveBeenCalled();
});
it("should not effect other functions", function() {
expect(bar).toEqual(123);
});
it("when called returns the requested value", function() {
expect(fetchedBar).toEqual(1001);//执行callFake方法,返回1001
});
});
it('TEST emailValidator() works', async () => {
spyOn(api, "checkEmail").and.callFake((email) => {//specify callFake
return new Promise( (resolve, reject) => {
if(email!=='test@gmail.com'){
resolve({"status":200})
}else {
let response = {}
response.data = [{"email":"Existió"}]
reject({'response':response})
}
})
});
let result0 = vm.emailValidator('')
expect(result0).toEqual(['El correo electrónico es requerido\n'])
let result1 = vm.emailValidator('wrong text')
expect(result1).toEqual(['Correo electrónico inválido'])
let result2 = await vm.emailValidator('test@gmail.com')
expect(result2).toEqual(['Existió'])
})
作者:孙进不后退
链接:http://www.jianshu.com/p/5254b4b1a5de
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。