[英]Sinon/Mocha test with async ajax calls didn't return promises
我正在为我的客户端 api use karma
with Mocha
和Sino
编写一些测试。 但我坚持获取异步过程。
import api from '../../../src/api';
import stubData from '../data';
import axios from 'axios';
/* eslint-disable prefer-arrow-callback,func-names */
describe('API test', function () {
before(function () {
this.server = sinon.fakeServer.create();
});
after(function () {
this.server.restore();
});
it('Should return cart with provided token', function (done) {
this.server.respondWith("GET", "/cart",
[200, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]']);
axios.get('/cart')
.then(function (response) {
console.log(response);
done();
})
.catch(function (error) {
console.log(error);
done();
});
this.server.respond();
});
});
出于某种原因,我总是收到Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
来自Mocha
。 好像then
后axios.get()
不被执行从而done
也不会被调用。
我确实遵循了Mocha
文档中推荐的内容
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
我在这里做错了什么吗? 谢谢
似乎sinon 上有一个悬而未决的问题,说它不适用于 axios,这里似乎就是这种情况。
Axios 实际上并没有调用您的 fakeserver。 它似乎试图从字面上请求/cart
,这就是您超时的原因。
该用户用另一个名为 nock 的库替换了 fakeServer 他在这里提到了它
还有其他库允许您模拟请求。
我通常使用supertest npm , Github 。
Github README 中的示例
var request = require('supertest');
var express = require('express');
var app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'tobi' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});
看起来 sinon 存根仅适用于 axios 请求方法别名。 也就是说,如果您通过传递配置来使用 axios
axios(someConfig)
上面的方法好像不行。
但是使用方法别名,它似乎有效。
axios.get(url, params, config)
axios.post(url, data, config)
当我们做
sandbox.stub(axios, "get")
我认为这是在 axios 中对get
方法进行存根,但在第一种情况下,不会调用get/post/anyother
方法并且存根不起作用。 我可能在这方面错了。 但无论如何它对我有用。
@bring2dip 建议的答案是正确的,但如果您除了使用之外别无选择
axios(config)
然后你可以使用
axios.request(config)
在 test.ts 中你可以使用
sandbox.stub(axios, "request")
结果是一样的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.