簡體   English   中英

使用 JEST 測試快速路線

[英]Testing express routes with JEST

我想用 JEST 測試我的快速 API 端點。

下面是我的 Express API 代碼。

routs.ts

// Get release notes
routes.get('/release-notes', (req, res) => {
  request.get({
    url: 'https://host.com/rest/api/content/search?cql=parent=209266565',
    json: true
  })
    .pipe(res);
});

export default routes;

上面的代碼將返回數據,但我想測試 API,使用 Mock 而不發出 API 請求

所以我手動創建了一個模擬響應,需要用它來驗證代碼。

Mock.ts

export const releaseNotesMockData = {
  'results': [
    {
      'id': '206169942',
      'type': 'page',
      'status': 'current',
      'title': 'Release 2018-10-18 Full Flow CM00294965',
    }]
};

使用下面的代碼,我點擊了真正的 API 並且測試通過了

describe('Test a 200', () => {
    test('It should respond with a 200 status', async () => {
      const response = await request(app).get('/release-notes');
      expect(response.statusCode).toBe(200);
    });
  });

問題是,我不想使用真正的 API 進行測試,而是想使用 Mocks 進行測試。

下面是我嘗試過的代碼,但沒有奏效。 請幫忙

routs.test.ts

describe('api test', () => {
  const url = '/release-notes';
  it('user GET should be 200', async () => {
    const result = await http({
      url,
      method: 'get'
    });
    expect(result).toBe('200');
  });
});

問題是您沒有嘲笑您正在導入的request模塊。

有關模擬的詳細信息,請參閱https://jestjs.io/docs/en/tutorial-async

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM