使用Nock.js在课堂上模拟Axios方法



我对编写单元测试很陌生,我正在努力弄清楚如何在发出 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,但无法弄清楚如何在模拟另一个模块中的调用的上下文中使用它。

这是我DataService如果有帮助的话:

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是否有效,但你可以使用axios-mock-adapter。

const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');
let dataService = new DataService;
describe('Data module with correct input', () => {
  let mock;
  before(() => {
    mock = new MockAdapter(axios);
  });
  afterEach(() => {
    mock.reset();
  });
  after(() => {
    mock.restore();
  });
  it('Should get a response from the server', async () => {
    mock.onGet('https://random.newsapis.com/search?section=recent-news&api-key=###############')
      .reply(200, 'Mock - response');
    const data = await dataService.getData('recent-news');
    expect(data).to.equal('Mock - response');
  });
});

我在测试中使用了 async/await,如果您想使用回调,请确保在 thencatch 块中调用done

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

最新更新