const name = "Name 0" const obj1 = { name: 'Name 1', getName: function() { return this.name } } const obj2 = { name: 'Name 2', getName: function() { return this.name } } const obj3 = { name: 'Name 3', other: { xname: 'xd', getName: function(){ return this } }, getName: () => { return this } } console.log(obj1.getName()) // normal call // this creates a new function, a copy of the referenced one (in this case obj2) const bindWithBind = obj1.getName.bind(obj2) // on the other hand, apply and call methods doesn't create a copy but just call a function // with the specified scope/context or 'this' reference. const obj2ResultWithApply = obj2.getName.apply(obj1) // call function with obj1 context const obj2ResultWithCall = obj1.getName.call(obj2) // call function with obj2 context console.log(bindWithBind()) console.log(obj2ResultWithCall) console.log(obj2ResultWithApply) // on obj3 we are showing that an anonymous function will get the context of the object that wraps // the function we are calling (in this case the global context) // and an arrow '=>' will not get any context at all console.log(obj3.other.getName()) console.log(obj3.getName()) // the only difference between apply and call is how we pass in arguments // apply expects and array of all the required parameters // and call expects parameters to be passed in inline const obj4 = { name: 'Abel Abner', salute: function(greeting) { return `${greeting} ${this.name}` } } const result4Apply = obj4.salute.apply(obj3, ['Hi']) const result4Call = obj4.salute.call(obj3, 'Hello') console.log(result4Apply) console.log(result4Call)
Useful references:
Make unit tests on functions that have 0 or minimal external dependecies (e.g. database or http interactions).
Tests a class or component with its external dependencies.
Drives an application trough the UI.
For unit testing universally we would have the following structure:
Look at the following unit test for details:
const toUpperCase = (str) => str.toUpperCase(); describe("some test", () => { it('has to blalala', () => { // arrange const sut = toUpperCase; const expected = "HOLA"; // act const actual = sut("hola"); // asserts expect(actual).toBe(expected); }) })
npx jest