如何在Jest中测试Javascript的toString()?

问题描述 投票:0回答:1

我正在尝试像下面这样的映射响应。

getData(){
     return data
     .map(subscription => ({
       id : subscription.id,
       productName: {
          toString: () => subscription.productName,
          name: subscription.productName
       }
    })
}

明确的转换,如 toString: () => subscription.productName 是一个要求。

我如何测试这个 toString()jest? 这条语句在测试中仍然没有被发现。

reactjs unit-testing jestjs enzyme
1个回答
1
投票

单元测试。

index.ts:

export const obj = {
  getData() {
    const data = [
      { id: 1, productName: 'github' },
      { id: 2, productName: 'reddit' },
    ];
    return data.map((subscription) => ({
      id: subscription.id,
      productName: {
        toString: () => subscription.productName,
        name: subscription.productName,
      },
    }));
  },
};

index.test.ts:

import { obj } from './';

describe('61953585', () => {
  it('should pass', () => {
    const datas = obj.getData();
    expect(datas).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          id: expect.any(Number),
          productName: expect.objectContaining({
            name: expect.any(String),
            toString: expect.any(Function),
          }),
        }),
      ]),
    );
    const productName1 = datas[0].productName.toString();
    expect(productName1).toBe('github');
    const productName2 = datas[1].productName.toString();
    expect(productName2).toBe('reddit');
  });
});

单元测试的结果。

 PASS  stackoverflow/61953585/index.test.ts (10.579s)
  61953585
    ✓ should pass (3ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.09s
© www.soinside.com 2019 - 2024. All rights reserved.