Last active
April 28, 2019 07:44
-
-
Save zzidante/be1d7a147cdae6ff5f6a591ea27b70a4 to your computer and use it in GitHub Desktop.
A very basic implementation of `expect` as seen in mocha/jasmine test libraries to help new coders understand some of the magic behind testing and method/property chaining.
This file contains hidden or 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
// A super simple no-edge case version of the `expect` function | |
// as seen in mocha/jasmine test environments. | |
// Long form | |
// step one: define a function called `expect` which takes one value. | |
// This value is intended to be the return value of a function. | |
const expect = function(actualValue) { | |
// assign a property onto `expect` called 'equalsTo' which is | |
// itself a function taking one argument (using `this` keyword | |
// which references the object itself in this case the function | |
// `expect`, since its uses the `function` keyword in its declaration). | |
// Properties can be assigned onto fns since functions are just a | |
// slightly special object (object is a collection of {key: value} pairs). | |
this.equalsTo = function(expectedValue) { | |
// `equalsTo` returns true or false depending on if `===` comparsion | |
// is successful. | |
return actualValue === expectedValue | |
} | |
// return the `expect` function with the `equalsTo` property which we can now call. | |
// It basically returns a "tranformed" version of itself which can dynamically change | |
// depending on the input of `actualValue`. | |
return this | |
} | |
// Arrow function internal | |
const expect = function(actualValue) { | |
this.equalsTo = (expectedValue) => { | |
return actualValue === expectedValue | |
} | |
return this | |
} | |
// 1-line auto-return arrow function | |
const expect3 = function(actualValue) { | |
this.equalsTo = expectedValue => actualValue === expectedValue | |
return this | |
} | |
// No THIS version. | |
// Return a plain object instead with an `equalsTo` key which corresponds | |
// to a short form anonymous function. `expect4` is basically a function | |
// which returns a partially filled function using its own argument `actualValue`. | |
const expect4 = function(actualValue) { | |
return { | |
equalsTo: expectedValue => expectedValue === actualValue | |
} | |
} | |
// To use, all the same. | |
expect('bob').toEqual('bob'); // => true | |
expect('bob').toEqual('tom'); // => false | |
expect2('bob').toEqual('bob'); // => true | |
expect2('bob').toEqual('tom'); // => false | |
expect3('bob').toEqual('bob'); // => true | |
expect3('bob').toEqual('tom'); // => false | |
expect4('bob').toEqual('bob'); // => true | |
expect4('bob').toEqual('tom'); // => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment