测试控制台日志功能

时间:2019-07-19 10:00:15

标签: node.js jestjs

  1. 我有一个打印字符串的函数

  2. 我想测试该函数是否实际打印提供的字符串

我理解这应该起作用的方式是: 1.将日志存储在var中 2.断言存储在var中的内容要达到我的期望

const log = 'hello2';

let myFunction = (log) => {
    console.log(log);
    };
myFunction(log);

const {myFunction} = require('../function-conversion');

test('Function prints message: "hello"', () => {
    expect(myFunction(log).toBe(console.log("hello")))
});

函数打印消息:“ hello”(1毫秒)

函数打印消息:“ hello”

  

ReferenceError:未定义日志

     

在Object.log中(测试 /function-conversion.test.js:4:20)

     

console.log ../function-conversion.js:11 hello2

2 个答案:

答案 0 :(得分:0)

下面的行有错误:

  

expect(myFunction(log).toBe(console.log(“ hello”)))

在调用函数myFunction(log)时,您应该传递任何字符串,而不是未在任何地方声明到function-conversion.test.js之类的"hello"文件中的log变量。

我没有环境,所以无法测试。但是您可以做的是:

describe('SearchResultsComponent', () => {
  let spy;
  
  let myFunction = (log) => {
    console.log(log);
  };
  myFunction(log);
  
  beforeAll(async () => {
    spy = jest.fn();
  });

  test('Function prints message: "hello"', () => {
    const log = 'hello';
    spy = jest.spyOn(console, 'log');
    myFunction(log);
    expect(spy).toHaveBeenCalled();
    expect(spy.calls.argsFor(0)).toEqual(['hello']);
  });
});

答案 1 :(得分:0)

我稍微提高了初始功能。 万一应该测试console.log消息,他应该将字符串推入数组。

let arrayOfMessages = [];
let functionThatPrintsTheArrayOfMessages = () => {
// pushing the messages to the array can be done when invoking the function as in line 19
//  console.log(message.push('hello','hi'));
    for (let i in arrayOfMessages){
    console.log(arrayOfMessages[i])
    };
    return arrayOfMessages;
};
functionThatPrintsTheArrayOfMessages(arrayOfMessages.push('hello', 'hi')); 

这是开玩笑的测试。

test('Function prints message: "hello", "hi"', () => {
expect(functionThatPrintsTheArrayOfMessages()).toContain('hello')

expect(functionThatPrintsTheArrayOfMessages()).toContain('hi')

expect(functionThatPrintsTheArrayOfMessages()).toEqual(['hello', 'hi'])
});

我想知道这是否正确以及其他测试方法。参与开玩笑。

相关问题