Supertest: проверьте, что произошло после res.send () - PullRequest
0 голосов
/ 19 ноября 2018

Я делаю POST, чтобы создать элемент и отправить вновь созданный элемент в ответ клиенту.

async (req, res, next) => {
  const item = await createItem(xx, yy, zz);
  res.send(201, item);
}

Теперь я также хочу отправлять уведомления после создания элемента , а также после ответа клиенту - чтобы сделать запрос как можно быстрее.

async (req, res, next) => {
  const item = await createItem(xx, yy, zz);
  res.send(201, item);

  sendNotification(item);
}

Если я хочу проверить это с помощью jest + supertest, это будет выглядеть так:

test('return 201', () => {
  const app = require('./');
  return request(app)
    .post('/api/items')
    .send({})
    .expect(201)
    .then(response => {
      // test something more
    });
}

Но как я могу проверить, был ли вызван sendNotification()?

1 Ответ

0 голосов
/ 19 ноября 2018

Вы можете использовать mocking в Jest, чтобы следить за функцией sendNotification() и утверждать, что она была вызвана. Простой пример:

const sendNotification = require('./sendNotification');
const sendNotificationSpy = jest.spyOn(sendNotification);

test('return 201', () => {
  const app = require('./');
  return request(app)
    .post('/api/items')
    .send({})
    .expect(201)
    .then(response => {
      // test something more
      expect(sendNotificationSpy).toHaveBeenCalled();
    });
}
...