Skip to content

Instantly share code, notes, and snippets.

@seagalputra
Last active January 28, 2022 18:05
Show Gist options
  • Save seagalputra/70df88b263556b60015217ede71880ed to your computer and use it in GitHub Desktop.
Save seagalputra/70df88b263556b60015217ede71880ed to your computer and use it in GitHub Desktop.
Sample Jest testing with modules
class Axios {
post() {
return true;
}
}
class Gateway {
constructor() {
this.api = new Axios();
}
}
exports.default = new Gateway();
const Gateway = require("./gateway").default;
const main = () => {
const result = Gateway.api.post();
if (!result) {
throw new Error("failed");
}
return;
};
module.exports = main;
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