【问题标题】:Mock busboy with jest开玩笑的模拟服务员
【发布时间】:2019-11-06 15:19:00
【问题描述】:

我在index.js 中设置了如下的快速 POST 路由

  import * as Busboy from 'busboy';
  public publish = async (req: Request, res: Response) => {
    const busboy = new Busboy({ headers: req.headers });
    const pl = { title: '' };
    busboy.on('field', (fieldname, val) => {
      switch (fieldname) {
        case 'title':
          pl.title = val;
          break;
      }
    });
    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      // Process files
    });
    busboy.on('finish', async () => {
      // Process request
      res.send({payload: pl});
    });
  } 

在测试index.test.js 使用玩笑我如何模拟这个模块,以便我可以验证包含表单字段title 在请求中发送的响应?

目前我使用jest.mock('busboy');,但没有任何东西因此被调用。

jest.mock('busboy');
let service: ServiceController;
describe('Mosaic Research Capture Service', () => {
  it('should publish', async () => {
    service = new ServiceController();
    const req = {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      body: {}
    };
    const res = {
      send: jest.fn()
    };
    await service.publish(req, res);
  });
});

React 客户端调用这个请求如下

 const formData = new FormData();
 formData.append('title', 'SomeTitle');
 const header = {
   credentials: 'include',
   'Content-Type': 'multipart/form-data',
 };
 const response =  await axios.post('/publish, formData, header); 

【问题讨论】:

    标签: javascript node.js jestjs busboy


    【解决方案1】:

    您需要一个“技巧”来模拟 event-listener 操作。作为一个问题https://github.com/airbnb/enzyme/issues/426

    您多次滥用async/await,如果您使用 Promises,请使用这些关键字。

    这是我对您的案例的建议更新:

    index.js :只需删除所有 async 关键字

     import * as Busboy from 'busboy';
      public publish = (req: Request, res: Response) => {
        const busboy = new Busboy({ headers: req.headers });
        const pl = { title: '' };
        busboy.on('field', (fieldname, val) => {
          switch (fieldname) {
            case 'title':
              pl.title = val;
              break;
          }
        });
        busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
          // Process files
        });
        busboy.on('finish', () => {
          // Process request
          res.send({payload: pl});
        });
      } 
    

    index.test.js

    import { ServiceController } from "./handler";
    import * as Busboy from 'busboy';
    
    jest.mock('busboy');
    describe('Mosaic Research Capture Service', () => {
      let service: ServiceController;
      const mockedEvenMap = {};
    
      beforeAll(() => {
        Busboy.mockImplementation(() => {
          return { // mock `on` event of Busby instance
            on: (event, callback) => {
              mockedEvenMap[event] = callback;
            },
          };
        });
    
        service = new ServiceController();
      });
    
      afterAll(() => {
        Busboy.mockRestore();
      });
    
      it('should publish', () => {
        const expectedTile = "MY_TITLE";
        const filenameToTest = 'title';
    
        const req = {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          body: {}
        };
        const res = {
          send: jest.fn()
        };
        service.publish(req, res); // remove await
    
        // fire simulate event
        mockedEvenMap['field'](filenameToTest, expectedTile);
        mockedEvenMap['finish']();
    
        // you expect send function will be call with a payload with includes the title
        expect(res.send).toBeCalledWith({ payload: {title: expectedTile} });
      });
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 2020-03-05
      • 1970-01-01
      相关资源
      最近更新 更多