【发布时间】:2016-04-12 15:29:01
【问题描述】:
我正在尝试在 Mocha 测试中使用 sinon 对 angular 的 $http 进行简单的模拟。
但是无论我怎么尝试,我的间谍都没有任何结果。
searchResource.typeAhead 是我正在测试的函数。它根据它的参数调用 $http,我想确保请求是正确的。
searchResource.typeAhead 返回一个承诺,但我尝试将检查代码放入 .then() 中,但它永远不会执行。
suite('Search Resource', function() {
var injector = angular.injector(['cannonball-client-search', 'cannonball-client-core']);
var searchResource = injector.get('SearchResource');
suite('#typeAhead()', function () {
setup(function () {
this.server = sinon.fakeServer.create();
this.server.respondWith('GET',
config.endpoints.search.typeAhead,
[200, {'Content-Type': 'application/json'}, '[{ "id": 12, "comment": "Hey there" }]']);
this.spyhttp = sinon.spy(injector.get('$http'));
});
teardown(function () {
this.server.restore();
});
test('positive', function (done) {
searchResource.typeAhead(
'expl',
[{entityType: 'itementity'}],
[{createdBy: 'Eric'}, {createdBy: 'Tal'}],
10
);
this.server.respond();
expect(this.spyhttp.calledWith({
method: 'get',
url: config.endpoints.search.typeAhead +
'?query=expl&filter=entityType:itementity&orfilter=createdBy:Eric&orfilter=createdBy:Tal&limit=10'
})).to.be.true();
done();
});
});
});
【问题讨论】:
-
尝试使用
$httpBackend~ docs.angularjs.org/api/ngMock/service/$httpBackend -
简短的回答是你不使用 sinon 来模拟
$http。请参阅@Phil 的资源以了解您需要使用的内容。它基于 ng 框架调用,因此您会发现使用它进行测试要容易得多。 -
好的,所以我“不” - 你能解释为什么我不应该这样做吗?诗乃应该可以嘲讽什么吧?为什么不用 $http?
标签: angularjs unit-testing mocha.js sinon sinon-chai