【问题标题】:Jest: Test for function passed into object fails with 'Received: serializes to the same string'开玩笑:对传递给对象的函数的测试失败并显示“已接收:序列化为相同的字符串”
【发布时间】:2020-09-18 14:41:54
【问题描述】:

我有一个函数,它接收一个对象数组并返回一个新的对象数组,简化如下:

const injectArray = (arr, fn) => {
  arr.map((el) => ({
    ...el,
    fn: () => fn(el),
  }));
};

对此的测试如下所示:

const mockFn = jest.fn();

describe('injectArray()', () => {
  it('returns a new array with the function injected into the objects', () => {
    expect(injectArray([{
      name: 'John Doe',
      age: 25
    }], mockFn)).toEqual([{
      name: 'John Doe',
      age: 25,
      fn: () => mockFn();
    }]);
  });
});

测试失败

Expected: [{"name": "John Doe", age: 25, "fn": [Function mockFn]}]
Received: serializes to the same string

当我将测试更改为 toContainEqual() 我得到

Expected value: [{"name": "John Doe", age: 25, "fn": [Function mockFn]}]
Received array: [{"name": "John Doe", age: 25, "fn": [Function mockFn]}] 

我相信 Jest 无法比较序列化函数,因此会失败,但在这个特定用例中,我需要将函数传递给对象,如何避免这种情况?

【问题讨论】:

    标签: javascript arrays unit-testing oop jestjs


    【解决方案1】:

    你是对的,jestjs 无法比较序列化的函数。你可以使用expect.any(constructor)

    例如

    index.ts:

    const injectArray = (arr, fn) => {
      return arr.map((el) => ({
        ...el,
        fn: () => fn(el),
      }));
    };
    
    export {injectArray}
    

    index.test.ts:

    import {injectArray} from './'
    
    const mockFn = jest.fn();
    
    describe('injectArray()', () => {
      it('returns a new array with the function injected into the objects', () => {
        expect(injectArray([{
          name: 'John Doe',
          age: 25
        }], mockFn)).toEqual([{
          name: 'John Doe',
          age: 25,
          fn: expect.any(Function)
        }]);
      });
    });
    

    带有覆盖率报告的单元测试结果:

     PASS  src/stackoverflow/63957885/index.test.ts
      injectArray()
        ✓ returns a new array with the function injected into the objects (4ms)
    
    ----------|----------|----------|----------|----------|-------------------|
    File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    ----------|----------|----------|----------|----------|-------------------|
    All files |       80 |      100 |    66.67 |       75 |                   |
     index.ts |       80 |      100 |    66.67 |       75 |                 4 |
    ----------|----------|----------|----------|----------|-------------------|
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        5.249s, estimated 13s
    

    【讨论】:

    • @Jacob 此外,您需要测试匿名函数以达到 100% 的测试覆盖率
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2017-02-11
    • 2021-06-26
    • 2021-01-24
    • 2018-02-13
    • 2020-07-14
    相关资源
    最近更新 更多