rogervinas / tests-everywhere
🤠 Tests, Tests Everywhere!
JavaScript testing this simple Hello World with Jest
Show me the code
Implementation
- Create
HelloMessage
class in HelloMessage.js:
class HelloMessage {
text = "Hello World!";
}
- Create
HelloConsole
class in HelloConsole.js:
class HelloConsole {
print(text) {
console.log(text);
}
}
- Create
HelloApp
class in HelloApp.js:
class HelloApp {
constructor(helloMessage, helloConsole) {
this.helloMessage = helloMessage;
this.helloConsole = helloConsole;
}
printHello() {
this.helloConsole.print(this.helloMessage.text);
}
}
- Create main function in Main.js that wraps it all together:
const HelloMessage = require("./HelloMessage");
const HelloConsole = require("./HelloConsole");
const HelloApp = require("./HelloApp");
const message = new HelloMessage();
const console = new HelloConsole();
const app = new HelloApp(message, console);
app.printHello();
Test
Following Jest > Getting Started guide ...
- Test
HelloMessage
in HelloMessage.test.js:
describe("HelloMessage", () => {
it("should return hello world", () => {
const message = new HelloMessage();
expect(message.text).toBe("Hello World!");
});
});
- Test
HelloApp
in HelloApp.test.js:
// 2.1 Mock ./HelloMessage module
jest.mock("./HelloMessage");
// 2.2 Mock ./HelloConsole module
jest.mock("./HelloConsole");
describe("HelloApp", () => {
it("should print hello message", () => {
const messageText = "Hello Test!";
// 2.3 Set mock implementation to be returned
// anytime new HelloMessage() is called
HelloMessage.mockImplementation(() => {
return {
text: messageText,
};
});
// 2.4 Create a HelloMessage
// that will be a mock thanks to 2.1 and 2.2
const message = new HelloMessage();
// 2.5 Create a HelloConsole
// that will be a mock thanks to 2.3
const console = new HelloConsole();
// 2.6 Create a HelloApp, the one we want to test, passing the mocks
const app = new HelloApp(message, console);
// 2.7 Execute the method we want to test
app.printHello();
// 2.8 Verify HelloConsole mock print() method
// has been called once with "Hello Test!"
expect(console.print).toHaveBeenCalledTimes(1);
expect(console.print).toHaveBeenCalledWith(messageText);
});
});
- Test output should look like:
> jest
PASS ./HelloMessage.test.js
PASS ./HelloApp.test.js
Test Suites: 2 passed, 2 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.229 s
Ran all test suites.
Happy Testing! 💙
Top comments (0)