【问题标题】:How to test if the type of the result is a javascript 'function' in Jest?如何测试结果的类型是否是 Jest 中的 javascript“函数”?
【发布时间】:2018-06-12 13:29:04
【问题描述】:

如何正确测试(使用jest)结果是否是一个实际的JavaScript函数?

describe('', () => {
    it('test', () => {
        const theResult = somethingThatReturnsAFunction();
        // how to check if theResult is a function
    });
});

我找到的唯一解决方案是像这样使用typeof

    expect(typeof handledException === 'function').toEqual(true);

这是正确的方法吗?

【问题讨论】:

  • 是的;你会怎么做呢?我可能会在 LoDash 的 isFunction 之类的东西中完成检查,但这是次要的(因为我几乎总是有一个 lodash 依赖项)。
  • 我认为有一种方法可以通过 jest api,例如 expect(result).toBe('function') 或 idk 与 toBe 相关的东西。感谢@DaveNewton 的回答
  • 这会将它与字符串function 进行比较,这不是您想要的。不过,可能有一个函数类型匹配器;我只是不知道。

标签: javascript unit-testing jestjs


【解决方案1】:

您可以使用toBe匹配器来检查typeof运算符的结果是否为function,请参见示例:

describe("", () => {
  it("test", () => {
    const somethingThatReturnsAFunction = () => () => {};
    const theResult = somethingThatReturnsAFunction();
    expect(typeof theResult).toBe("function");
  });
});

【讨论】:

  • Error: expect(received).toBe(expected) // Object.is 相等 Expected: "function" Received: [Function anonymous]
  • 嗨@Rob,现在刚刚使用Node v12 和Jest v26 对其进行了测试,我的示例仍然有效。请检查您的 Node & Jest 版本。我在一个空白文件中使用它,除了从我上面的示例中截取的代码之外没有别的。
  • @Rob 缺少 typeof 关键字。应该是expect(typeof received).toBe(expected)
【解决方案2】:

Jest 提供了一种检查所提供值类型的好方法。

您可以使用.toEqual(expect.any(<Constructor>)) 来检查提供的值是否属于构造函数的类型:

describe('', () => {
  it('test', () => {
    const theResult = somethingThatReturnsAFunction()
    expect(theResult).toEqual(expect.any(Function))
  })
})

构造函数的其他示例有:String & Number

【讨论】:

    猜你喜欢
    • 2020-01-05
    • 2020-09-03
    • 2020-05-27
    • 1970-01-01
    • 2014-01-20
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    相关资源
    最近更新 更多