javascript文件:
const getDisplayNews = () => new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("GET", "https://newsapi.org/v2/everything?sources=al-jazeera-english&apiKey=**********************", true);
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
resolve(JSON.parse(request.response));
} else if (request.status === 404) {
reject("Error! Not Found");
}
};
request.send();
});
我需要在这里模拟onload函数。我已经完成了打开功能。 这是代码:
describe("javascript file", () => {
describe("The exposed displaynews function", () => {
let resolveSpy;
let rejectSpy;
beforeEach(() => {
XMLHttpRequest.prototype = jasmine.createSpyObj("XMLHttpRequestSpy", ["open"]);
});
it("returns a promise object", () => {
expect(getDisplayNews()).toEqual(jasmine.any(Promise));
});
});
it("should call proper API", () => {
getDisplayNews();
expect(XMLHttpRequest.prototype.open).toHaveBeenCalledWith(
"GET", "https://newsapi.org/v2/everything?sources=al-jazeera-english&apiKey=**************", true);
});
如何针对onload函数执行此操作。
谢谢
答案 0 :(得分:0)
这实际上取决于您是单元测试还是集成测试。对于简单的单元测试,正面和负面反应都应该有2个测试
您可以通过以下方式实现:
存根示例应为:
it('Should Resolve', () => {
spyOn(moduleName,'load').and.callFake(() => {
return 200;
});
expect(XMLHttpRequest.prototype.load).toBe(200);
})
it('Should NOT Resolve', () => {
spyOn(moduleName,'load').and.callFake(() => {
return 400;
});
expect(XMLHttpRequest.prototype.load).toBe(400);
})