如何使用Jest测试Json.parse

时间:2020-02-28 06:22:48

标签: javascript typescript jestjs ts-jest

我是Jest的新手,正在尝试异步测试。而且我正在尝试介绍Json.Parse,它引发了如下所述的异常。

错误消息

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

代码

 public async callDataSourceCommand(dialogData: any, RecipeId: string) {

   const gridItems = await this.dataSourceService.myPromiseMethod(id, collection);
   this.updateGrid(JSON.parse(gridItems));

 }
 private updateGrid(gridItems: any) {}

模拟数据

public get dataSourceServiceMock(): any = {
  return {
    myPromiseMethod: function () {
        return Promise.resolve({
             selectedOrder: {
                earlierStartTime: '2/5/2020',
                __id: 'orderId123'
            },
            Collection: [{
                __id: 'b1order 1',
                resName: 'New recipe_V1.0',
                plannedQuantity: '3',
                resId: 'ns=6;s=4/ProjectData/1',
                actualQuantity: '1',
                description: 'batchDesc',
             }]
           });
       }
   }
}

测试套件

it('1. Should execute ', async() => {

  const myDialogApp: DialogApp = TestBed.get(DialogApp);
  myDialogApp.selectedOrder = selectedOrder;
  myDialogApp.RecipeId = Recipe.__id;

  jest.spyOn(dataSourceServiceMock, 'myPromiseMethod');

  await myDialogApp.callDataSourceCommand(dialogData, RecipeId);

  expect(dataSourceServiceMock.myPromiseMethod).toHaveBeenCalled();
});

2 个答案:

答案 0 :(得分:1)

好吧,您只需将响应存根并按以下方式传递

public get dataSourceServiceMock(): any = {
  return {
    myPromiseMethod: function () {
        return Promise.resolve(JSON.stringify({
             selectedOrder: {
                earlierStartTime: '2/5/2020',
                __id: 'orderId123'
            },
            Collection: [{
                __id: 'b1order 1',
                resName: 'New recipe_V1.0',
                plannedQuantity: '3',
                resId: 'ns=6;s=4/ProjectData/1',
                actualQuantity: '1',
                description: 'batchDesc',
             }]
           }));
       }
   }
}

希望这会有所帮助!

答案 1 :(得分:0)

这是单元测试解决方案:

index.ts

class Service {
  private dataSourceService;
  constructor(dataSourceService) {
    this.dataSourceService = dataSourceService;
  }
  public async callDataSourceCommand(dialogData: any, RecipeId: string) {
    const id = '1';
    const collection = [];
    const gridItems = await this.dataSourceService.myPromiseMethod(id, collection);
    this.updateGrid(JSON.parse(gridItems));
  }
  private updateGrid(gridItems: any) {}
}

export { Service };

datasourceService.ts

class DataSourceService {
  public myPromiseMethod(id, collection) {
    return JSON.stringify({});
  }
}

export { DataSourceService };

index.test.ts

import { Service } from './';

describe('60446313', () => {
  it('should pass', async () => {
    const gridItemsMock = JSON.stringify({
      selectedOrder: {
        earlierStartTime: '2/5/2020',
        __id: 'orderId123',
      },
      Collection: [
        {
          __id: 'b1order 1',
          resName: 'New recipe_V1.0',
          plannedQuantity: '3',
          resId: 'ns=6;s=4/ProjectData/1',
          actualQuantity: '1',
          description: 'batchDesc',
        },
      ],
    });
    const dataSourceServiceMock = {
      myPromiseMethod: jest.fn().mockResolvedValueOnce(gridItemsMock),
    };
    const parseSpy = jest.spyOn(JSON, 'parse');
    const service = new Service(dataSourceServiceMock);
    await service.callDataSourceCommand('dialogData', '1');
    expect(dataSourceServiceMock.myPromiseMethod).toBeCalledWith('1', []);
    expect(parseSpy).toBeCalledWith(gridItemsMock);
  });
});

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

 PASS  stackoverflow/60446313/index.test.ts
  60446313
    ✓ should pass (9ms)

----------|---------|----------|---------|---------|-------------------
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:        4.509s, estimated 6s