我正在使用 Jasmine 框架创建一些 Javascript 测试。我正在尝试使用 spyOn()
方法来确保已调用特定函数。这是我的代码
describe("Match a regular expression", function() {
var text = "sometext"; //not important text; irrelevant value
beforeEach(function () {
spyOn(text, "match");
IsNumber(text);
});
it("should verify that text.match have been called", function () {
expect(text.match).toHaveBeenCalled();
});
});
但是我得到了一个
Expected a spy, but got Function
错误。我试图删除 spyOn(text, "match");
行,它给出了同样的错误,似乎函数 spyOn()
没有工作是吗应该。
有什么想法吗?
最佳答案
我发现为了测试像 string.match 或 string.replace 这样的东西,你不需要 spy ,而是声明包含你正在匹配或替换的内容的文本并调用 beforeEach 中的函数,然后检查响应等于您期望的响应。这是一个简单的例子:
describe('replacement', function(){
var text;
beforeEach(function(){
text = 'Some message with a newline \n or carriage return \r';
text.replace(/(?:\\[rn])+/g, ' ');
text.replace(/\s\s+/g, ' ');
});
it('should replace instances of \n and \r with spaces', function(){
expect(text).toEqual('Some message with a newline or carriage return ');
});
});
这样就成功了。在这种情况下,我还会跟进一个替换以将多个间距减少到单个间距。此外,在这种情况下,beforeEach
没有必要,因为您可以在 it
中使用赋值和调用您的函数声明和你的期望之前。它应该与 string.match
类似地工作如果你把它翻过来阅读更多类似 expect(string.match(/someRegEx/).toBeGreaterThan(0);
的操作.
希望这对您有所帮助。
-C§
编辑:或者,您可以压缩您的 str.replace(/regex/);
或 str.match(/regex/);
进入调用的函数并使用 spyOn
在那里使用 spyOn(class, 'function').and.callthrough();
在你的beforeEach
并使用类似 expect(class.function).toHaveBeenCalled();
的东西和 var result = class.function(someString);
(而不只是调用函数)将允许您使用 expect(class.function(someString)).toEqual(modifiedString);
测试返回值替换或 expect(class.function(someString)).toBeGreaterThan(0);
为了比赛。
如果这提供了更深入的见解,请随时 +1。
谢谢,
C§
关于javascript - spyOn:期待一个 spy ,但得到了功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29367030/