mercredi 29 août 2018

Python like function mock in JavaScript

With Python it's so easy to mock a function that is used in the function under test.

# my_module.py
def function_a():
    return 'a'


def function_b():
    return function_a() + 'b'



# tests/test_my_module.py
from unittest import TestCase
from unittest.mock import patch

from my_module import function_b


class MyModuleTestCase(TestCase):
    @patch('my_module.function_a')
    def test_function_b(self, mock_function_a):
    mock_function_a.return_value = 'c'

    assertEqueal(function_b(), 'cb')

Is something like this possible in JavaScript using, for example, jest?

# myModule.js
function myFunctionA() {
  return 'a';
}

export function myFunctionB() {
  return myFunctionA() + 'b';
}


# __test__/test.myModule.js
import { myFunctionB } from './myModule';

describe('myModule tests', () => {
  test('myFunctionB works', () => {
    // Mock `myFunctionA` return value here somehow. 
    expect(myFunctionB()).toBe('cb')
  });
});

I've read https://github.com/facebook/jest/issues/936 and still have no idea how to do it as there are so many (hacky) suggestions (some of them ~2 years old).

Aucun commentaire:

Enregistrer un commentaire