2

I am new to Jest and i am trying test async await. And I am trying to cover Json.Parse and it is throwing an exception like below mentioned.

Error Message

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

Code

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

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

 }
 private updateGrid(gridItems: any) {}

Mock Data

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

Test Suite

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 Answers 2

1

Well, you can simply stub the response and pass it as below

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

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

Here is the unit test solution:

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);
  });
});

Unit test results with coverage report:

 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.