我是 jasmine
的新手,这是我的 src
文件,我在其中创建了 Auth
类
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 !";
}
}
现在我想测试 jasmine 的 toHaveBeenCalled()
匹配器。这是我写的
it("should be able to Login", function () {
spyOn(authobj);
expect(authobj.Login('abc', 'abc')).toHaveBeenCalled();
});
但是它说 undefined() 方法不存在
最佳答案
查看您的用例,我不建议在此处使用 toHaveBeenCalled
。 toHaveBeenCalled
在您需要测试回调(异步)或结合模拟的情况下很有用。
将 Auth.prototype.Login
中发生的所有事情都视为对“外部世界”不可见的实现细节。您不应该测试实现细节。这引发了两个问题。
为什么我不应该测试实现细节?
这让重构变得困难。假设您出于某些原因想要用 underscore.isEmpty
替换 Auth.prototype.isEmpty
。几天后,您决定将 underscore
完全替换为 lodash
。这将迫使您更改测试三次。将所有阻碍您轻松重构的因素都视为“不行”。
我应该测试什么?
公共(public) 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');
});
});
关于javascript - 试图理解 Jasmine 的 toHaveBeenCalled() 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16787351/