简体   繁体   English

用开玩笑的方式模拟服务员

[英]Mock busboy with jest

I have an express POST route set-up in index.js as following我在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});
    });
  } 

In test index.test.js using jest how do i mock this module in such a way that i can validate the response containing the form field title sent in request?在使用 jest 的测试index.test.js ,我如何模拟这个模块,以便我可以验证包含请求中发送的表单字段title的响应?

Currently i use jest.mock('busboy');目前我使用jest.mock('busboy'); but nothing gets invoked due to this.但因此没有被调用。

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

The React client invokes this request as follows 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); 

You need a "trick" to mock a event-listener action.您需要一个“技巧”来模拟event-listener操作。 As a issue https://github.com/airbnb/enzyme/issues/426作为一个问题https://github.com/airbnb/enzyme/issues/426

You abuse async/await many times, just use these keywords if you working with Promises.您多次滥用async/await ,如果您使用 Promises,只需使用这些关键字。

Here is my suggest update for your case:这是我针对您的案例的建议更新:

index.js : Just remove all async keywords 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} });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM