【问题标题】:Mocked function is `undefined` but unit test doesn't fail模拟函数是“未定义”,但单元测试不会失败
【发布时间】:2017-11-22 12:22:24
【问题描述】:

在我的单元测试套件中,我有以下模拟:

  beforeEach(() => {
        NativeModules.MyModule = {
            myMethod: jest.fn()
        };
     })

还有这个使用它的单元测试:

 it('has some functionality', () => {
    console.log(JSON.stringify(NativeModules.MyModule.myMethod));
    expect(NativeModules.MyModule.myMethod).toHaveBeenCalledTimes(1);
});

console.log 函数打印 undefined 但测试通过。

但是,如果我添加这一行:

expect(undefined).toHaveBeenCalledTimes(1);

测试将失败并显示以下消息:

expect(jest.fn())[.not].toHaveBeenCalledTimes()

jest.fn() value must be a mock function or spy.
Received: undefined

那么如果NativeModules.MyModule.myMethodundefined,那么单元测试怎么能通过呢?

【问题讨论】:

  • 不能JSON.stringify函数

标签: javascript react-native jestjs


【解决方案1】:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

如果未定义,则在转换过程中遇到函数或符号 它要么被省略(当它在一个对象中找到时)要么被审查到 null(当它在数组中找到时)。 JSON.stringify 也可以 传入“纯”值时返回未定义,例如 JSON.stringify(function(){}) 或 JSON.stringify(undefined)。

如果您直接记录模拟函数 (console.log(NativeModules.MyModule.myMethod) 而不是记录 console.log(JSON.stringify(NativeModules.MyModule.myMethod)) 你应该会看到你期望的输出。

例如:

console.log(() => {})
console.log(JSON.stringify(() => {}))

【讨论】:

  • 是否有替代JSON.stringify 的方法来打印这些对象?
  • @octavian,你想看到什么输出?如果上面没有给你想要的输出(例如在 REPL 中),你可能会使用 Function.prototype.toString(): console.log(fn.toString())
猜你喜欢
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
  • 2020-01-08
相关资源
最近更新 更多