0

假设我有一个 expressjs 应用程序、应用程序、设置和一个端点,如下所示: app.get('/endpoint', endPointFunction)

该功能设置如下:

const axios = require('axios');
var endpointFunction = async(req, res) =>{
try{
  const a = await get5LatestAnime();
  console.log(a.titles); 
  const b = await get5LatestManga();
  console.log(b.titles); 
  res.status(200).json({watch: a.titles, read:b.titles});
}catch(err){
  console.log(err); 
  res.status(400).json({err:err.message});
}

};

async function get5LatestAnime(ballot){
 const { data } = await axios.get('https://anime.website.com/'); 
 return data;
}
async function get5LatestManga(confirmationNumber){
  const { data } = await axios.get(`https://manga.website.com/`); 
  return data;
}

因此,假设您运行它时所有这些都打印/工作,但是假设您想运行一些单元测试,仅存根第一个 axios 请求。

describe('Moxios', () => {
            
            beforeEach(() => {
                moxios.install();
                moxios.stubRequest('https://anime.website.com', {
                    status: 200,
                    response: [{titles:[
"Naruto", "Bleach", "Fate/Stay Night", "Death Note", "Code Geass"]}]
                });
                
            });

             afterEach(() => {
                moxios.uninstall()
            });
            it('should return a 200 and confirmation status', function () {
                return request(app)
                    .post('/endpoint')
                    .expect(200, {watch: [
"Naruto", "Bleach", "Fate/Stay Night", "Death Note", "Code Geass"], read: [...titles from the manga website]})
                    });
            });
        });

在类似的场景(我无法发布的代码)中,发生的情况是 moxios 正确地存根请求,但其他 axios 请求有超时错误,无论我允许超时持续多长时间。( Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves)。

如果我不使用 moxios(如果我注释掉与 moxios 相关的东西),我只测试所有超时的函数,但需要存根的端点的工作原理。

有谁知道如何解决这个问题?

4

1 回答 1

0

您需要小心url传递给moxios.stubRequest方法的字符串。应该是https://anime.website.com/,不是https://anime.website.com

此外, 的响应get5LatestAnime是一个数组。因为您将响应模拟为数组:

response: [{ titles: ['Naruto', 'Bleach', 'Fate/Stay Night', 'Death Note', 'Code Geass'] }],

因此,您需要从而不是在您的控制器中访问该titles属性。a[0].titlesa.titlesendpointFunction

这是一个完整的工作示例:

app.js

const axios = require('axios');
const express = require('express');
const app = express();

var endpointFunction = async (req, res) => {
  try {
    const a = await get5LatestAnime();
    console.log(a);
    const b = await get5LatestManga();
    console.log(b);
    res.status(200).json({ watch: a[0].titles, read: b[0].titles });
  } catch (err) {
    console.log(err);
    res.status(400).json({ err: err.message });
  }
};

async function get5LatestAnime(ballot) {
  const { data } = await axios.get('https://anime.website.com/');
  return data;
}
async function get5LatestManga(confirmationNumber) {
  const { data } = await axios.get(`https://manga.website.com/`);
  return data;
}

app.get('/endpoint', endpointFunction);

module.exports = { app };

app.test.js

const { app } = require('./app');
const moxios = require('moxios');
const request = require('supertest');
const { expect } = require('chai');

describe('Moxios', () => {
  beforeEach(() => {
    moxios.install();
  });

  afterEach(() => {
    moxios.uninstall();
  });
  it('should return a 200 and confirmation status', (done) => {
    moxios.stubRequest('https://anime.website.com/', {
      status: 200,
      response: [{ titles: ['Naruto', 'Bleach', 'Fate/Stay Night', 'Death Note', 'Code Geass'] }],
    });
    moxios.stubRequest('https://manga.website.com/', {
      status: 200,
      response: [{ titles: ['Naruto', 'Bleach', 'Fate/Stay Night', 'Death Note', 'Code Geass'] }],
    });

    request(app)
      .get('/endpoint')
      .expect('Content-Type', 'application/json; charset=utf-8')
      .expect(200)
      .end((err, res) => {
        if (err) {
          return done(err);
        }
        expect(res.body).to.deep.equal({
          watch: ['Naruto', 'Bleach', 'Fate/Stay Night', 'Death Note', 'Code Geass'],
          read: ['Naruto', 'Bleach', 'Fate/Stay Night', 'Death Note', 'Code Geass'],
        });
        done();
      });
  });
});

测试结果:

  Moxios
[ { titles:
     [ 'Naruto',
       'Bleach',
       'Fate/Stay Night',
       'Death Note',
       'Code Geass' ] } ]
[ { titles:
     [ 'Naruto',
       'Bleach',
       'Fate/Stay Night',
       'Death Note',
       'Code Geass' ] } ]
    ✓ should return a 200 and confirmation status (107ms)


  1 passing (121ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   88.89 |      100 |     100 |   88.89 |                   
 app.js   |   88.89 |      100 |     100 |   88.89 | 13-14             
----------|---------|----------|---------|---------|-------------------
于 2020-11-06T03:45:28.367 回答