如何使用jasmine.js测试控制台输出? [英] How can I use jasmine.js to test for console output?

查看:838
本文介绍了如何使用jasmine.js测试控制台输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理以下文字:用于Web开发人员的专业JavaScript,由Nicholas Zakas提供
,我将使用Jasmine.js测试示例。

I'm working through the text: Professional JavaScript for Web Developers by Nicholas Zakas and I'm testing the examples with Jasmine.js.

我现在可以通过指定一个返回值来测试函数的输出,但是当我想要返回多个数据时遇到麻烦。

I can currently test the output of a function by specifying a return a value, but I'm running into trouble when there are multiple pieces of data that I want to return.

教科书使用alert()方法,但这是麻烦的,我不知道如何测试警报。我想知道是否有一种方法来测试console.log()输出。例如:

The textbook uses the alert() method, but this is cumbersome and I don't know how to test for alerts. I was wondering if there was a way to test for console.log() output. For instance:

function_to_test = function(){
    var person = new Object();
    person.name = "Nicholas";
    person.age = 29;

    return(person.name);    //Nicholas
    return(person.age);     //29
});

我知道我可以让它们作为一个字符串返回,但是对于更复杂的例子,我想可以测试以下内容:

I know I can have them return as one string, but for more complicated examples I'd like to be able to test the following:

function_to_test = function(){
    var person = new Object();
    person.name = "Nicholas";
    person.age = 29;

    console.log(person.name);    //Nicholas
    console.log(person.age);     //29
});

Jasmine测试看起来像:

The Jasmine test looks something like:

it("should test for the function_to_test's console output", function(){
    expect(function_to_test()).toEqual("console_output_Im_testing_for");
});

有没有简单的方法来做这个我只是失踪?

Is there a simple way to do this that I'm just missing? I'm pretty new to coding so any guidance would be appreciated.

推荐答案

有些事情是错误的代码。正如所指出的,拥有多个return语句不会工作。此外,当定义一个新对象时,最好使用对象字面语法来使用 new Object

There are a couple of things that are wrong with your code above. As pointed out, having multiple return statement will not work. Also, when defining a new object, it is preferable to use the object literal syntax over using new Object.

你通常会做的更像这样:

What you would normally do is something more like this:

var function_to_test = function () {
  var person = {
    name : "Nicholas",
    age : 29
  };

  return person;
};

使用上面的函数,有几种方法可以测试。一个使用 Jasmine间谍来模拟console.log对象。

Using the function above, there are a couple of ways you could test this. One it to mock out the console.log object using Jasmine Spies.

it("should test for the function_to_test's console output", function () {
    console.log = jasmine.createSpy("log");
    var person = function_to_test();
    expect(console.log).toHaveBeenCalledWith(person);
});

另一种是测试函数的实际输出。

The other is to test the actual output of the function.

it("should return a person", function () {
    var person = function_to_test();
    expect(person).toEqual({ name : "Nicholas", age : 29 });
});

这篇关于如何使用jasmine.js测试控制台输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆