我正在使用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();
});
});
但我得到了
预期是间谍,但得到了功能
错误。我试图删除spyOn(text, "match");
行,但它给出了相同的错误,似乎功能spyOn()
不起作用。有什么想法吗?
我发现,为了测试像string.match或string.replacement这样的东西,你不需要间谍,而是需要声明包含匹配或替换内容的文本,并调用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(/ss+/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
语句中使用赋值并在预期之前调用函数。如果您将它翻转过来读起来更像expect(string.match(/someRegEx/).toBeGreaterThan(0);
,那么它应该与string.match
操作类似。
希望这能有所帮助。
-C§
编辑:或者,您可以将str.replace(/regex/);
或str.match(/regex/);
压缩到一个被调用的函数中,并在那里使用spyOn
,在beforeEach
中使用spyOn(class, 'function').and.callthrough();
,并使用类似expect(class.function).toHaveBeenCalled();
和var result = class.function(someString);
的东西(而不仅仅是调用函数)。这将允许您用expect(class.function(someString)).toEqual(modifiedString);
测试返回值以进行替换,或用expect(class.function(someString)).toBeGreaterThan(0);
测试匹配。
如果这能提供更深入的见解,请随意拨打+1。
谢谢,
C§
您得到该错误是因为它在expect
方法上失败。expect
方法期望传入一个间谍,但它没有。要解决此问题,请执行:
var text = new String("sometext");
您的测试用例仍然会失败,因为您没有在任何地方调用match方法。如果希望它通过,则需要在it
函数内部调用text.match(/WHATEVER REGEX/)。