【问题标题】:How to test Json.parse using Jest如何使用 Jest 测试 Json.parse
【发布时间】:2020-06-12 05:43:24
【问题描述】:

我是 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();
});

【问题讨论】:

    标签: javascript typescript jestjs ts-jest


    【解决方案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',
                 }]
               }));
           }
       }
    }
    
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      这里是单元测试解决方案:

      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
      

      【讨论】:

        猜你喜欢
        • 2017-01-04
        • 2017-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        • 2015-10-12
        • 2021-02-14
        相关资源
        最近更新 更多