我一直在阅读关于Jasmine 2.0中异步方法的变化,但我仍然无法理解这个概念,所以也许有人可以帮我重新设计以下代码:
it("Description", () => {
// Arrange
spyOn($, "ajax").and.callFake((params) => {
params.success(someObject);
});
waitsFor(() => {
return someList[0] != null;
});
// Act
viewModel.init();
// Assert
runs(() => {
expect(someList[0].id).toEqual(someObject.id);
});
});
viewModel.init()
方法是填充someList
答案 0 :(得分:1)
这样的事情:
it("Description", done => {
// Arrange
spyOn($, "ajax").and.callFake((params) => {
params.success(someObject);
});
// Act
viewModel.init();
somePromise.then(() => {
expect(someList[0].id).toEqual(someObject.id);
done();
});
});
等待的快速和脏替换:
function waitsAndRuns(condition: () => boolean, timeout: number, onTimeout: () => void, onDone: () => void) {
var timeoutHandle = setTimeout(() => {
clearInterval(intervalHandle);
onTimeout();
}, timeout);
var intervalHandle = setInterval(() => {
if (condition()) {
clearInterval(intervalHandle);
clearTimeout(timeoutHandle);
onDone();
}
}, 10);
}
规范中的用法:
waitsAndRuns(() => someList[0] != null, 1000, done, () => {
expect(someList[0].id).toEqual(someObject.id);
done();
});
答案 1 :(得分:0)
谢谢,Artem,我提出了这个解决方案:
ajaxSpy = spyOn($, 'ajax');
describe("Text", () => {
function bindSpyAndPromise(JSONResult: any[]): MyViewModel {
var d = $.Deferred();
d.resolve(JSONResult);
ajaxSpy.and.returnValue(d.promise());
return new MyViewModel();
}
it("Text", () => {
viewModel = bindSpyAndPromise(someObject);
var promisse = viewModel.init();
promisse.then(
() => {expect(someList[0].id).toEqual(someObject.id);
});
});
})