jest test ajax
Wed Feb 01 2023 13:23:45 GMT+0000 (Coordinated Universal Time)
Saved by
@lafcha
#javascript
#jest
#test
const APP = (() => {
var userData = null;
const myURL = "http://stackoverflow.com";
const getData = () => {
$.ajax({
type: "GET",
url: myURL,
success: obj.handleSuccess,
error: obj.handleError,
});
};
const handleError = () => {
console.log("ERROR");
};
const handleSuccess = (data) => {
userData = data;
console.log(userData);
};
const render = () => {
return "<div>some stuff</div>";
};
const obj = {
getData,
handleError,
handleSuccess,
render,
};
return obj;
})();
module.exports = APP;
const APP = require("../ajax");
describe("Ajax", () => {
beforeEach(() => {
jest.restoreAllMocks();
});
it("Data should load", () => {
const ajaxSpy = jest.spyOn($, "ajax");
APP.getData();
expect(ajaxSpy).toBeCalledWith({
type: "GET",
url: "http://stackoverflow.com",
success: expect.any(Function),
error: expect.any(Function),
});
});
it("should handle success", () => {
const mUser = { userId: 1 };
const logSpy = jest.spyOn(console, "log");
APP.handleSuccess(mUser);
expect(logSpy).toBeCalledWith(mUser);
});
it("should handle error", () => {
const logSpy = jest.spyOn(console, "log");
APP.handleError();
expect(logSpy).toBeCalledWith("ERROR");
});
});
content_copyCOPY
Comments