我是新来的jasmine
这是我的src
我在其中创建的文件Auth
class
function Auth() {
}
Auth.prototype.isEmpty = function(str) {
return (!str || 0 === str.length);
}
Auth.prototype.Login = function (username , password) {
if (this.isEmpty(username) || this.isEmpty(password)) {
return "Username or Password cann't be blank ";
}
else {
return "Logged In !";
}
}
现在我想测试茉莉花的toHaveBeenCalled()
匹配器。这是我写的
it("should be able to Login", function () {
spyOn(authobj);
expect(authobj.Login('abc', 'abc')).toHaveBeenCalled();
});
但它说undefined() method does not exist
看看你的用例,我不建议使用toHaveBeenCalled
here. toHaveBeenCalled
在您想要测试回调(异步)或与模拟结合的情况下非常有用。
考虑里面发生的一切Auth.prototype.Login
作为“外部世界”不可见的实现细节。您不应该测试实现细节。这引发了两个问题。
为什么我不应该测试实现细节?
它使重构变得困难。假设您想更换Auth.prototype.isEmpty
由于某些原因underscore.isEmpty
。几天后你决定更换underscore
完全由lodash
。这将迫使您更改测试三次。将阻碍您轻松重构的一切视为“禁忌”。
我应该测试什么?
公共API。 “另一个世界”可见的一切。您的情况是“已登录!”和“用户名或密码不能为空”。
结果是 3 个测试:
describe('Login', function() {
it('returns "success" string when username and password are not empty', function() {
expect(new Auth().Login('non-empty', 'non-empty')).toBe('Logged In !');
});
it('returns "failure" string when username is empty', function() {
expect(new Auth().Login('', 'non-empty')).toBe('Username or Password cannot be blank');
});
it('returns "failure" string when password is empty', function() {
expect(new Auth().Login('non-empty', '')).toBe('Username or Password cannot be blank');
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)