Javascript 使用Nock.js在类上模拟Axios方法

Javascript 使用Nock.js在类上模拟Axios方法,javascript,node.js,mocha.js,tdd,axios,Javascript,Node.js,Mocha.js,Tdd,Axios,我对编写单元测试非常陌生,我正在努力解决如何在发出axios请求的es6类上测试方法。我一直在尝试使用nock,但是不管断言如何,测试都会通过。这就是我到目前为止一直在努力做的事情- let dataService = new DataService; describe('Data module with correct input', function () { before(function(){ nock('https://random.newsapis.com')

我对编写单元测试非常陌生,我正在努力解决如何在发出axios请求的es6类上测试方法。我一直在尝试使用nock,但是不管断言如何,测试都会通过。这就是我到目前为止一直在努力做的事情-

let dataService = new DataService;

describe('Data module with correct input', function () {
  before(function(){
    nock('https://random.newsapis.com')
      .get('search?section=recent-news&api-key=###############')
      .reply(200, 'Mock - response');
  });

  it('Should get a response from the server', function (done){
    dataService.getData('recent-news')
      .then(function(data){
        expect(data).to.equal('Mock - response');
      }).catch(err => {
        throw(err)
      });
    done();
  });
});
我尝试将done函数移到回调中,但没有效果。这是我用于其他异步代码的模式。我看过moxios,但不知道如何在另一个模块中模拟调用的上下文中使用它

这是我的
数据服务
,如果有帮助的话:

export default class dataService {
  getData = (section: string) => (
    new Promise(function (resolve, reject) {
      axios.get('https://random.newsapis.com/search?section=' + section + '&api-key=xxxx')
        .then(function (response) {
          return resolve(response.data.response);
        })
        .catch(function (reject) {
          errorModule(reject);
        });
     })
  )}

我很感激任何人能给我的建议!提前感谢

我不知道nock是否有效,但您可以使用

我在测试中使用了async/await,如果要使用回调,请确保在
块中调用
done
,然后
catch
块:

dataService.getData('recent-news')
  .then(function(data){
    expect(data).to.equal('Mock - response');
    done();
  }).catch(err => {
    done(err);
  });
dataService.getData('recent-news')
  .then(function(data){
    expect(data).to.equal('Mock - response');
    done();
  }).catch(err => {
    done(err);
  });