# ✅ Javascript Testing

3 min read, 506 words testingjavascriptspyonmockingstubjestfaking

Tests are lifeline for your code. A dirty code could always be refactored, but a broken code could not.

~ Sarah Dayan
  • Mocking Object faking
  • Test Stubs are mocks that helps you test. For Example, interface for sendEmail
  • mock objects are objects where you actually put asserts on test to determine test pass/fail status. For Example, test if sendEmail service wrote a success/failure log. We will mock logWriter in this scenario.
  • TDD forces you to think about writing testable code under various conditions

# 🐒 Why Mocking

  • Goal of mocking to avoid using any external service. Why would we want to do that?
    • to make tests run faster
    • to make tests more isolated
    • to make tests more independent and idempotent of each other
    • great for writing unittests
  • If our tests depends on some external service, then we might better call it integration test
  • Great of simulating scenarious like
    • What if database is empty?
    • what if databse is full?
    • what if delays are sec? *what if network is super slow? Or no network at all situation.

# 🎎 Mock Object

  • Track function calls, #instances created, results returned etc.
  • Erase the actual implementation of a function
  • what to assert on? values?
    • expect(value).toMatchSnapshot()

jest mocking function mock property

let car = 'some cat'
console.log(car);

/** REVIEW
 *
 * The jest object is automatically in scope within every test file.
 * The methods in the jest object help create mocks.
 * imported explicitly by via
 * import {jest} from '@jest/globals'.
 *
 * NOTE -> MOCKING aka Spying
 * 1. How the method was called
 * 2. What were the responses to each call
 *
 * https://jestjs.io/docs/en/mock-function-api#methods
 * https://jestjs.io/docs/en/jest-object#mock-functions
 * https://stackoverflow.com/questions/2665812/what-is-mocking
 *
 * How to create mock objects/functions?
 * 1. jest.fn(implementation)
 * 2. jest.spyOn(object, methodName)
 *
 * How to create test stubs? Indirections?
 * https://jestjs.io/docs/en/manual-mocks#mocking-user-modules
 *
 * NOTE -> Parameterized and concurrent tests
 * test.only
 * test.each(table)(name, fn, timeout)
 * test.todo(name)
 */

const timeout = 5000;

// beforeAll(SuiteSetup, timeout)
// beforeEach(TestSetup, timeout)
// afterEach(TestTeardown, timeout)
// afterAll(SuiteTeardown, timeout)

function sumFn (a, b) {
  return (a+b)
}

describe('dummy test suite', () => {
  test('both integer argumants', () => {
    // Mock sumFn Functionality
    const mockFn = jest.fn((x, y) => x+y);
    console.log(mockFn);
    // expect(actual).toBe(6)
  })
})

# ⏲ Timer Functions

The native timer functions (i.e., setTimeout, setInterval, clearTimeout, clearInterval) are less than ideal for a testing environment since they depend on real time to elapse.

jest.useFakeTimers();
// Fast-forward until all timers have been executed
jest.advanceTimersByTime(1000);
jest.clearAllTimers()

Enable fake timers by calling jest.useFakeTimers();. This mocks out setTimeout and other timer functions with mock functions. If running multiple tests inside of one file or describe block, jest.useFakeTimers(); can be called before each test manually or with a setup function such as beforeEach.

  • Callback is called after 1 second?

# 🌧 Good Questions

What should I test in a component?

what/how to test.

  1. HTML structure?
  2. CSS classes?
  3. View logic?
  4. Event Handlers?
  5. Lifecycle hooks?
  6. Methods, computed properties?
  7. Am I going for 100% coverage?
  8. Unit | Integration | e2e test?
  9. Use testing stub boilerplates snippets. saves time
What is the difference b/w jest.fn() and jest.spyOn()? (opens new window)

They both does the same job but in different ways.

spyOn - lets us create a mock from and existing class/method which we want to use in our test

jest.fn() - lets us create mock object from scratch. Usually we just plug in the return values without caring about the implementation.

Difference between jest.fn() and jest.mock()?
jest description
jest.fn() (opens new window) mocks objects and functions
jest.mock() (opens new window) mocks a module
How to mock JSON imports?

Use moduleNameMapper (opens new window) in settings to mock a json file import.

# Resources

Subscribe to our Newsletter

If you like my work and think it was helpful kindly support my work


Buy Me A Coffee