Created
December 11, 2020 14:01
-
-
Save drianoaz/f91c5374a74edabee90c32b42104084b to your computer and use it in GitHub Desktop.
Mock setTimeout jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.foo = (req, res) => { | |
const isSuccess = Math.random() < 0.5; | |
setTimeout(() => { | |
if (isSuccess) { | |
return res.send(201); | |
} | |
res.send(403); | |
}, 3000); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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