首页 > 解决方案 > 如何在 Jest 中测试 Javascript 的 toString()

问题描述

我正在尝试映射如下响应:

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

像这样的显式转换toString: () => subscription.productName是一项要求。

我该如何测试toString()jest?该声明在测试中仍未发现。

标签: reactjsunit-testingjestjsenzyme

解决方案


单元测试:

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

推荐阅读