用Jest测试匿名函数是否相等 [英] Testing anonymous function equality with Jest

查看:173
本文介绍了用Jest测试匿名函数是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用jest@20测试匿名函数的相等性?

Is there a way to test anonymous function equality with jest@20?

我正在尝试通过类似于以下的测试:

I am trying to pass a test similar to:

const foo = i => j => {return i*j}
const bar = () => {baz:foo(2), boz:1}

describe('Test anonymous function equality',()=>{

    it('+++ foo', () => {
        const obj = foo(2)
        expect(obj).toBe(foo(2))
    });

    it('+++ bar', () => {
        const obj = bar()
        expect(obj).toEqual({baz:foo(2), boz:1})
    });    
});

当前产生:

  ● >>>Test anonymous function equality › +++ foo

    expect(received).toBe(expected)

    Expected value to be (using ===):
      [Function anonymous]
    Received:
      [Function anonymous]

    Difference:

    Compared values have no visual difference.

  ● >>>Test anonymous function equality › +++ bar

    expect(received).toBe(expected)

    Expected value to be (using ===):
      {baz: [Function anonymous], boz:1}
    Received:
      {baz: [Function anonymous], boz:1}

    Difference:

    Compared values have no visual difference.

推荐答案

在这种情况下,无需重写逻辑以使用命名函数,除了在测试前声明函数<,例如

In such situation, without rewriting your logic to use named functions, you don't really have another choice other than declaring the function before the test, e.g.

const foo = i => j => i * j
const foo2 = foo(2)
const bar = () => ({ baz: foo2, boz: 1 })

describe('Test anonymous function equality', () => {
  it('+++ bar', () => {
    const obj = bar()
    expect(obj).toEqual({ baz: foo2, boz: 1 })
  });    
});

或者,您可以使用expect.any(Function):

检查obj.bar是否为任何功能:

Alternatively, you can check whether obj.bar is any function, using expect.any(Function):

expect(obj).toEqual({ baz: expect.any(Function), boz: 1 })

根据测试的上下文,这实际上可能更有意义.

which might actually make more sense depending on the context of the test.

这篇关于用Jest测试匿名函数是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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