gpt4 book ai didi

javascript - 使用 mocha chai 和 sinon 测试 promise

转载 作者:行者123 更新时间:2023-11-30 06:52:47 24 4
gpt4 key购买 nike

我想使用 mochachaisinon 测试我的 promise 解析处理程序和 promise 拒绝处理程序。此外,我有sinon-chai 插件和 sinon-stub-promise 插件设置。

这是我的 require 语句 block :

var chai = require('chai');
var expect = chai.expect;
var sinonChai = require('sinon-chai');
chai.use(sinonChai);
var sinon = require('sinon');
var sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);

这是我的测试套件:

describe('Connect to github users',function(done){

var api = require('../users'),
onSuccess = api.onSuccess,
onError = api.onReject;
console.dir(api);
//the idea is not to test the async connection,the idea is to test
//async connection but to test how the results are handled.
var resolveHandler,
rejectHandler,
getPromise,
result;

beforeEach(function(){
resolveHandler = sinon.spy(onSuccess);
rejectHandler = sinon.spy(onError);
getPromise = sinon.stub().returnsPromise();
});

it('must obtain the result when promise is successful',function(){
result = [...];//is an actual JSON array
getPromise.resolves(result);

getPromise()
.then(resolveHandler)
.catch(rejectHandler);

expect(resolveHandler).to.have.been.called();//error
expect(resolveHandler).to.have.returned(result);
expect(rejectHandler).to.have.not.been.called();
done();
});

afterEach(function(){
resolveHandler.reset();
rejectHandler.reset();
getPromise.restore();
});

});

我发现自己遇到了这个错误:

 Connect to github users must obtain the result when promise is successful:
TypeError: expect(...).to.have.been.called.toEqual is not a function
at Context.<anonymous> (C:\Users\vamsi\Do\testing_promises\test\githubUsersSpec.js:94:46)

最佳答案

sinon-with-promise package 应该符合你想要做的事情。我遇到了同样的问题(除了我不需要测试拒绝案例)并且结果很好。

关于javascript - 使用 mocha chai 和 sinon 测试 promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32411734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com