代码之家  ›  专栏  ›  技术社区  ›  jordan

恶作剧和间谍不适用

  •  0
  • jordan  · 技术社区  · 3 年前

    我有一个功能测试,可以确保我的一个API的代码正常工作。该代码的一部分向外部API发出请求。我希望这个调用被嘲笑,然而,我已经尝试了几乎所有我能在网上找到的实现mock的可能解决方案,但它似乎总是被调用。

    在测试中:

    const vendorOneOperations = require('~/server/vendor/vendorOne/operations');
    
    jest.mock('~/server/vendor/vendorOne/operations', () => ({
      ...(jest.requireActual('~/server/vendor/vendorOne/operations') as object),
      listItems: jest.fn().mockReturnValue({ results: [] }),
    }));
    

    在正在测试的服务中:

    import * as vendorOne from '~/server/vendor/vendorOne';
    
    const { results: items } = await vendorOne.operations.listItems(itemIds);
    console.log('ITEMS: ', items);
    

    ~/server/vendor/vendorOne/index.ts

    export { default as client, getValidToken } from './client';
    export * as schema from './schema';
    export * as operations from './operations';
    export * as constants from './constants';
    

    ~/server/vendor/vendorOne/operations/index.ts

    ...
    export { default as listItems } from './listItems';
    ...
    

    ~/server/vendor/vendorOne/operations/listItems.ts

    import qs from 'query-string';
    import { operation } from './abstract';
    
    export default operation({
      method: 'get',
      path: '/api/items',
      config: (ids: string[]) => ({
        params: { item_ids: ids },
        paramsSerializer: (params) => qs.stringify(params, { arrayFormat: 'none' }),
      })
    });
    

    运行测试时,我看到:

      console.log
        ITEMS: [
          ... // actual items from API 
        ]
    
          at getItems (src/server/services/vendorService/common/getItems.ts:37:11)
    
    0 回复  |  直到 3 年前