Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zzidante/edc83249f8639f526c8beec02f3c0fb4 to your computer and use it in GitHub Desktop.
Save zzidante/edc83249f8639f526c8beec02f3c0fb4 to your computer and use it in GitHub Desktop.
A simple (and assumed) example of how Jasmine works under the hood using Describe->It->Expect->EqualsTo pattern. Meant to help to understand the workings of tests rather than being accurate to Jasmine itself.
// Run the file `node simple_and_fake_jasmine_describe_it_expect_equalsto_pattern.js` from containing folder.
// Should receive 1 passing and 1 failing test (as noted by text color -> Green/Red).
// To understand: read from the call site and work backwards.
// -- Fancy console printing like tests do (no emojis yet) -- //
const printToConsole = function(text, status = 'normal', padding = false) {
const CC = {
Reset: '\x1b[0m',
Underscore: '\x1b[4m',
FgRed: '\x1b[31m',
FgGreen: '\x1b[32m',
};
let pad = '';
if (padding) pad = ' ';
if (status === 'success') {
console.log(`${pad}${CC.FgGreen}%s${CC.Reset}`, text);
} else if (status === 'normal') {
console.log(`${pad}${CC.Underscore}%s${CC.Reset}`, text);
} else if (status === 'failure') {
console.log(`${pad}${CC.FgRed}%s${CC.Reset}`, text);
} else {
console.log('Error calling printToConsole status');
}
};
// -- Testing suite -- //
// -- State of the result of the test -- //
// -- This should probably be a private internal variable inside the test module -- //
// -- but I was lazy so it just gets overwrite globally in this file. -- //
let testingStateResult = null;
const describe = function(logTitle, context) {
printToConsole(logTitle);
context();
testingStateResult = null;
};
const it = function(logTitle, context) {
context();
printToConsole(logTitle, testingStateResult, true);
};
const expect = function(actualValue) {
this.toEqual = (expectedValue) => {
const results = actualValue === expectedValue;
if (results) {
testingStateResult = 'success';
} else {
testingStateResult = 'failure';
}
return results;
};
return this;
};
// -- Function to be tested -- //
const hello = function(name) {
return `Hello ${name}`;
};
// -- Test Examples -- //
describe(
'hello()',
function() {
// -- Successful Test -- //
it(
'returns a spaced concatenated string: Hello Adora',
function() {
expect(hello('Adora')).toEqual('Hello Adora');
}
);
// -- Failing Test -- //
it(
'returns a spaced concatenated string: Hello Catra',
function() {
expect(hello('Catra')).toEqual('HelloCatra');
}
);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment