Jasmine 测试 Node.js 异步模块
Jasmine Testing Node.js Async modules
I\m 尝试为我编写的一些代码编写单元测试,我 运行 遇到的问题是我希望在执行函数后调用我的模拟回调,但我的测试失败了它永远不会被调用。
describe("Asynchronous specs", function() {
var mockNext;
beforeEach(function() {
mockNext = jasmine.createSpy('mockNext');
var res;
parallelRequests.APICall(testObject[0], null, mockNext);
});
it("callback spy should be called", function () {
expect(mockNext).toHaveBeenCalled();
});
});
正在测试的功能很简单:
function APICall(options, res, next) {
request(options, callback);
function callback(error, response, body) {
if (error) {
if (error.code === 'ETIMEDOUT') {
return logger.error('request timed out: ', error);
next(error);
}
logger.error('request failed: ', error);
next(error);
}
next(null);
}
}
我怀疑的问题是茉莉花在 API 调用中执行模拟回调之前测试预期,因为请求的异步性质。我试过使用其他人建议使用 done() 和标志但没有运气。希望在这件事上得到一些指导。
您的 beforeEach
代码是异步的。当您的 beforeEach
逻辑完成时,您必须告诉 yasmin。您可以通过传递给每个测试的回调方法 done
来解决这个问题。试试这个:
describe("Asynchronous specs", function() {
var mockNext;
beforeEach(function(done) {
parallelRequests.APICall(testObject[0], null, function(){
mockNext = jasmine.createSpy('mockNext');
mockNext();
done();
});
});
it("callback spy should be called", function () {
expect(mockNext).toHaveBeenCalled();
});
});
I\m 尝试为我编写的一些代码编写单元测试,我 运行 遇到的问题是我希望在执行函数后调用我的模拟回调,但我的测试失败了它永远不会被调用。
describe("Asynchronous specs", function() {
var mockNext;
beforeEach(function() {
mockNext = jasmine.createSpy('mockNext');
var res;
parallelRequests.APICall(testObject[0], null, mockNext);
});
it("callback spy should be called", function () {
expect(mockNext).toHaveBeenCalled();
});
});
正在测试的功能很简单:
function APICall(options, res, next) {
request(options, callback);
function callback(error, response, body) {
if (error) {
if (error.code === 'ETIMEDOUT') {
return logger.error('request timed out: ', error);
next(error);
}
logger.error('request failed: ', error);
next(error);
}
next(null);
}
}
我怀疑的问题是茉莉花在 API 调用中执行模拟回调之前测试预期,因为请求的异步性质。我试过使用其他人建议使用 done() 和标志但没有运气。希望在这件事上得到一些指导。
您的 beforeEach
代码是异步的。当您的 beforeEach
逻辑完成时,您必须告诉 yasmin。您可以通过传递给每个测试的回调方法 done
来解决这个问题。试试这个:
describe("Asynchronous specs", function() {
var mockNext;
beforeEach(function(done) {
parallelRequests.APICall(testObject[0], null, function(){
mockNext = jasmine.createSpy('mockNext');
mockNext();
done();
});
});
it("callback spy should be called", function () {
expect(mockNext).toHaveBeenCalled();
});
});