Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest.fn() value must be a mock function or spy

I have a function in a module called button-actions that is called when a user clicks a back button. I want to test the backButtonActions method directly but need to mock up the leaveApp and displayById methods inside backButtonActions that get called.

Here is my button-actions.js file method.

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 tests 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 a string of 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 should be running to get this to work ?

like image 683
me-me Avatar asked Jun 13 '17 15:06

me-me


1 Answers

You need to spy on the backButtonActions function, either via jasmine's spyOn method or via Jest's jest.spyOn method

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

like image 140
Mike Bell Avatar answered Sep 28 '22 02:09

Mike Bell