Skip to content

Instantly share code, notes, and snippets.

@drianoaz
Created December 11, 2020 14:01
Show Gist options
  • Save drianoaz/f91c5374a74edabee90c32b42104084b to your computer and use it in GitHub Desktop.
Save drianoaz/f91c5374a74edabee90c32b42104084b to your computer and use it in GitHub Desktop.
Mock setTimeout jest
exports.foo = (req, res) => {
const isSuccess = Math.random() < 0.5;
setTimeout(() => {
if (isSuccess) {
return res.send(201);
}
res.send(403);
}, 3000);
};
const controller = require("./MyController");
function mockGlobalFunc(funcName, funcMock) {
const funcOriginal = global[funcName];
global[funcName] = funcMock;
return () => {
global[funcName] = funcOriginal;
}
}
const setTimeoutRestoreFunction = mockGlobalFunc('setTimeout', callback => callback());
describe("controller", () => {
afterAll(() => {
setTimeoutRestoreFunction();
});
describe("controller.finish", () => {
it("success response", async () => {
jest.spyOn(global.Math, 'random').mockReturnValueOnce(0.12);
const fakeResponse = {
send: jest.fn(),
};
cartController.foo(undefined, fakeResponse);
expect(fakeResponse.send).toHaveBeenCalledWith(201);
});
it("error response", async () => {
jest.spyOn(global.Math, 'random').mockReturnValueOnce(0.60);
const fakeResponse = {
send: jest.fn(),
};
cartController.foo(undefined, fakeResponse);
expect(fakeResponse.send).toHaveBeenCalledWith(403);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment