DEV Community

Justin L Beall
Justin L Beall

Posted on • Edited on

3 1

I wrote a JavaScript Unit Test today... Mock Import Time Function

I am using Redux inside of a create-react-app application, jest included.

Task

Add a new REST resource named wadget to the existing reducers function. Using TDD.

// reducers.js
import {combineReducers} from 'redux'

import widget from './widget'

export default combineReducers({
    widget
})
Enter fullscreen mode Exit fullscreen mode

As a kata today, I wanted to mock out this function that executes at import time. I am still learning the JavaScript ecosystem. I could do this in Python...

Let's pause for a moment... because it sounds pretty ridiculous. Languages allow imports to execute non-encapsulated code procedurally. Side effects within these files alter the state of the running system when the instruction pointer links to the file.

Let's connect to a database when we import the DAO base file!

Test

I struggled with this for a little bit today. I asked a question on stack overflow.

// reducers.test.js
import redux from 'redux'
import widget from './widget'

describe('Use jest', () => {
    afterEach(() => {
        jest.resetModules()
    });

    test('first test', () => {
        jest.doMock('redux');

        require('./reducers');
        let {combineReducers} = require('redux');

        expect(combineReducers).toBeCalledWith({"widget": widget})
    });
});
Enter fullscreen mode Exit fullscreen mode

Coding Steps

At this point, since I have the invocation of combinedReducers isolated, I can update my test to expect another resource type, wadget.

(red) FAIL Test
import widget from './widget'
import wadget from './wadget'
// ...
expect(combineReducers).toBeCalledWith({
  "widget": widget,
  "wadget": wadget
})
Enter fullscreen mode Exit fullscreen mode
(green) SUCCESS
// reducers.js
import {combineReducers} from 'redux'

import widget from './widget'
import widget from './wadget'

export default combineReducers({
    widget,
    wadget
})
Enter fullscreen mode Exit fullscreen mode

agile2018endorsement

Top comments (0)

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️