Jest.fn () value must be mock function or spy

I have a function in a module called a button action that is called when the user clicks the back button. I want to test the backButtonActions method directly, but you need to mock the leaveApp and displayById methods inside the backButtonActions that are called.

Here is my file method button-actions.js .

export function backButtonActions( label, page ){      //, page
    console.log("LABEL = ", label, "  page = ", page);
    switch( label ){
        case 'step1':
            page.leaveApp();
            break;
        case 'step2':
            page.displayById();
            break;
    }
}

      

I'm new to testing, so I might be missing something very simple. Below is my test.js file

   window.$ = require('jquery');
    import {backButtonActions} from '../button-actions';


    describe('Button Actions', () => {

        const page = {}

        beforeEach(() => {

            page.leaveApp = jest.fn(() => "leave");
            page.displayById = jest.fn(() => "Display");

            document.body.innerHTML =
                '<div>' +
                '  <button class="btn-back" />' +
                '</div>';

                 $('.btn-back').click((event, label) =>{
                     backButtonActions( label, page );
                 });




    });
    it('backButtonActions requires a string of either "step1" or "step2"', () => {

        $('.btn-back').trigger('click', 'step1');

         expect(backButtonActions).toBeCalled();
         expect(backButtonActions).toBeCalledWith("step1" || "step2");
    });
})

      

When I run the above test, I get the following error.

● Button Actions> backButtonActions requires the line either "Step 1" or "Step 2"

expect(jest.fn())[.not].toBeCalled()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function backButtonActions]

  at Object.<anonymous> (test/js/spec/create/button-actions.test.js:64:50)

      

Is there something else I have to run to get this to work?

+3


source to share


1 answer


You need to keep track of the function backButtonActions

either with the jasmine method spyOn

or with the Jest methodjest.spyOn



https://facebook.github.io/jest/docs/jest-object.html#jestspyonobject-methodname

+4


source







All Articles