【问题标题】:Class method returns undefined [duplicate]类方法返回未定义的[重复]
【发布时间】:2018-07-12 13:28:52
【问题描述】:

我正在用 JavaScript 编写一个发送特定 URL 的 HTTP 请求的类。我正在尝试使用 Mocha 测试该类,但由于某种原因,方法 fetchUrl() 返回undefined。我似乎无法弄清楚为什么。我一天前就开始用 JavaScript 编写代码,因此我仍在努力学习和适应它。

 fetchUrl () {
    var request = require('request')
    var res
    request(this.url, function (error, response, body) {
      console.log('error:', error) // Print the error if one occurred
      if (response.statusCode !== 200) {
        console.log('received status code other than 200 OK')
        this.error = true
      }
      res = response
      console.log('statusCode:', response && response.statusCode) // Print the response status code if a response was received
      // console.log('body:', body) // Print the HTML for the requested url.
      this.html = body
    })
    return res
  }

describe('Test Http request to google.com', function () {
  it('should return 200', function (done) {
    assert.equal(httpCon.fetchUrl().statusCode, 200)
    done()
  })
})

【问题讨论】:

标签: javascript node.js mocha.js chai node-request


【解决方案1】:

您应该使用Nock libray 来模拟 HTTP 请求。

const axios = require('axios');
module.exports = {
   getUser(username) {
     return axios
        .get(`https://api.github.com/users/${username}`)
        .then(res => res.data)
        .catch(error => console.log(error));
    }
};

这里是测试用例:

describe('Get User tests', () => {
    beforeEach(() => {
       nock('https://api.github.com')
         .get('/users/octocat')
         .reply(200, response);
    });
});

有关更多详细信息,您可以查看:mocking-http 也可以查看 SO 的this 答案。 source

【讨论】:

    【解决方案2】:

    我认为你应该只在回调中返回 res ,否则它将返回 undefined ,因为程序一直在运行...... https://developer.mozilla.org/en-US/docs/Glossary/Callback_function 你可能想看看回调函数

    【讨论】:

    • 它仍然返回未定义,我认为是因为该方法变成了 void 类型
    猜你喜欢
    • 2017-07-06
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2019-10-01
    • 2023-04-11
    相关资源
    最近更新 更多