【问题标题】:Function not getting called in Mocha testMocha 测试中未调用函数
【发布时间】:2017-08-14 22:43:41
【问题描述】:

我正在开发一个 Express.js 应用程序。当前的功能是通过发布请求创建约会并从第三方 API 获取和保存数据,然后在后续请求中发送更新的 API 数据。该功能已完全正常工作,但在测试中,获取 API 数据的函数没有被调用。

创建约会的路线:

app.post('/schedule', requestHandler.postSchedule);

创建约会的请求处理程序:

requestHandler.postSchedule = function (req, res) {
  let appointment = {
    // posted data
  };

  new Appointment(appointment)
    .save()
    .then(newAppointment => {
      if(req.body.cityName && req.body.cityName !== '') {
        console.log('req.body.cityName', req.body.cityName);
        weatherHelper.addNewCityWeatherData(req.body.cityName);
      }
      return newAppointment;
    })
    .then(newAppointment => {
      // do some other stuff
      res.send(newAppointment);
    })
    .catch(err => {
      error(err);
    });
};

添加天气数据的功能:

exports.addNewCityWeatherData = (city) => {
  console.log('City in addNewCityWeatherData', city);
  getCurrentTrackingCities(cities => {
    if(cities.indexOf(city) < 0) {
      console.log(city + ' data not in weather');
      getWeatherData(city, data => {
        console.log('Got weather data');
        addWeatherDataToDB(city, data);
      });
    } else {
      console.log('City exists');
    }
  });
};

从 API 获取天气数据的功能:

getWeatherData = (city, callback) => {
  console.log('getWeatherData called', city);
  let url = `http://api.apixu.com/v1/forecast.json?key=${weatherApiKey}&q=${city}&days=${10}`
  request(url, (err, res, body) => {
    console.log('Weather data received body');
    callback(body);
  });
};

在测试时,此功能失败并打印所有控制台日志,但“天气数据接收正文”和后续函数中的日志除外。

这是我的测试:

describe.only('Weather data', function() {
  let requestWithSession = request.defaults({jar: true});

  let hashedPass = bcrypt.hashSync('testpass', null);

  beforeEach((done) => {
    new User({
      'name': 'Test User',
      'email': 'testuser@test.com',
      'password': hashedPass
    })
    .save()
    .then(() => {
      let options = {
        'method': 'POST',
        'uri': testHost + '/login',
        'form': {
          'email': 'testuser@test.com',
          'password': 'testpass'
        }
      };
      requestWithSession(options, (err, res, body) => {
        done();
      });
    });
  }); // beforeEach

  afterEach((done) => {
    // remove test stuff from db
  }); // afterEach

  it('Adds weather data when an appointment with new city is posted', (done) => {
    let options = {
      'method': 'POST',
      'uri': testHost + '/schedule',
      'form': {
        'title': 'Test title',
        'description': 'Test description',
        'start_date_time': '2017-07-19 01:00',
        'end_date_time': '2017-07-19 02:00',
        'cityName': 'New York',
        'isTrackingWeather': 'true'
      }
    };

    // post request to add appointment data
    requestWithSession(options, (err, res, body) => {
      if(err) {
        console.log('DatabaseError in Weather Data');
        throw {
          type: 'DatabaseError',
          message: 'Failed to create test setup data'
        };
      }

      let options = {
        'method': 'GET',
        'uri': testHost + '/allweather'
      };

      // subsequesnt request to get updated weather data
      requestWithSession(options, (err, res, body) => {
        let found = false;
        weatherData = JSON.parse(body);
        // console.log('weatherData in test', weatherData);
        weatherData.forEach(weather => {
          if(weather.location && weather.location.name === 'New York') {
            found = true;
          }
        });
        expect(found).to.be.true;
        done();
      });

    });
  });
}); // Weather Data

这是终端输出:

谁能告诉我我做错了什么?

【问题讨论】:

    标签: javascript express mocha.js


    【解决方案1】:

    当您运行测试时,测试套件向您的测试服务器发出请求,而在您的测试服务器中处理请求的代码向另一台主机发出另一个请求。

    您看不到'Weather data received body',因为您的测试服务器处理的请求没有等待测试服务器本身发出的请求。 addNewCityWeatherData 没有回调,也没有返回一个承诺,所以调用它的代码在不等待它完成的情况下继续它的快乐方式。您应该修改它以允许调用代码等待结果。

    另外,我没有看到您的测试服务器发起的请求中的数据是如何折叠回来自您的测试套件的请求中的。您可能还需要为此添加一些代码,除非addWeatherDataToDB(city, data); 以某种方式自动处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 2012-08-22
      • 2014-02-08
      • 2019-11-27
      • 1970-01-01
      相关资源
      最近更新 更多