【发布时间】:2018-03-07 14:55:17
【问题描述】:
我对编写单元测试还是很陌生,我正在努力弄清楚我应该如何在发出 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);
});
})
)}
感谢任何人对此的任何指点!提前致谢
【问题讨论】:
标签: javascript node.js mocha.js tdd axios