Last active
January 28, 2022 18:05
-
-
Save seagalputra/70df88b263556b60015217ede71880ed to your computer and use it in GitHub Desktop.
Sample Jest testing with modules
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
class Axios { | |
post() { | |
return true; | |
} | |
} | |
class Gateway { | |
constructor() { | |
this.api = new Axios(); | |
} | |
} | |
exports.default = new Gateway(); |
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 Gateway = require("./gateway").default; | |
const main = () => { | |
const result = Gateway.api.post(); | |
if (!result) { | |
throw new Error("failed"); | |
} | |
return; | |
}; | |
module.exports = main; |
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
describe("Sample test", () => { | |
it("test failure", () => { | |
jest.mock("./gateway"); | |
const mock = jest.fn(() => false); | |
require("./gateway").default.api.post = mock; | |
expect(() => require("./sample")()).toThrow("failed"); | |
}); | |
it("test success", () => { | |
jest.mock("./gateway"); | |
const mock = jest.fn(() => true); | |
require("./gateway").default.api.post = mock; | |
expect(() => require("./sample")()).not.toThrow("failed"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment