Как проверить Json .parse с помощью Jest - PullRequest
2 голосов
/ 28 февраля 2020

Я новичок в Jest и пытаюсь проверить asyn c жду. И я пытаюсь охватить 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 ]

1 голос
/ 28 февраля 2020

Ну, вы можете просто заглушить ответ и передать его, как показано ниже

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',
             }]
           }));
       }
   }
}

Надеюсь, это поможет!

0 голосов
/ 28 февраля 2020

Вот решение для модульного тестирования:

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
...