如何对以res.send结尾的javascript函数进行单元测试(200,object)

时间:2017-11-08 03:54:51

标签: javascript unit-testing asynchronous

我正在尝试对下面的函数getAllPeopleFromDB进行单元测试:

export const getAllPeopleFromDB = async (req, res) => {
  const people = await getAllAustralianPeopleFromDB();
  res.send(200, people);
};

问题是,我不知道如何在最后处理res.send(200,人)。

这是我的尝试(这可能有用也可能没用):

  // datastoreService.getAllAustralianPeopleFromDB = jest.fn().mockImplementation(() => (
  //   new Promise(resolve => resolve('stub'))
  // ));

  // describe('getAllPeopleFromDB', () => {
  //   test('that body contains people and has 200 status', (done) => {
  //     req = {};
  //     res = {};

  //     getAllPeopleFromDB(req, res).then((response) => {
  //       expect(response).toContain(['stub', 200]);
  //       done();
  //     });
  //   });
  // });

1 个答案:

答案 0 :(得分:1)

您可以在.send对象上定义res方法,该方法接受数据参数(正在发送的数据)并存储它,以便检查其值。您的测试代码目前会检查传递给.then()的数据,该数据为undefined,因为getAllPeopleFromDB无法解析值。

而是尝试:

describe('getAllPeopleFromDB', () => {
    test('that body contains people and has 200 status', (done) => {

        let responseData = ''
        const req = {};
        const res = {send: function(status, data) {responseData = data}};

        getAllPeopleFromDB(req, res).then(() => {
          expect(responseData).toContain('whatever');
          done();
        });
    });
});