UP | HOME

notes

1 bind, apply and call

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:

2 TDD

20220924_190154_aPeAz0.png

3 Tests

3.1 Types of tests

20220531_103404_3xunju.png

3.1.1 Unit tests

Make unit tests on functions that have 0 or minimal external dependecies (e.g. database or http interactions).

3.1.2 Integrations tests

Tests a class or component with its external dependencies.

  • Take longer to execute
  • Give you more confidence because it interacts with a database, for example.

3.1.3 End-to-end tests

Drives an application trough the UI.

  • gives you great confidence
  • But they are very slow.
  • An example of a program used to do this kind of tests, is selenium.

3.2 Tooling for tests

20220531_104113_H01DDK.png

3.3 Unit testing

For unit testing universally we would have the following structure:

  1. arrange
  2. act
  3. assert

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