Why isn't my Jest spy showing as called when I can see that it is?












1














I am trying to determine why exactly my Jest spy isn't being called when I can see that the spy is properly "injected" into my component? Here's my very simple example:



TestComponent.js



export default class TestComponent extends Component {
constructor(props) {
super(props);

this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
event && event.preventDefault();
console.log("handleSubmit called!");
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<button className="submit-button" type="submit">
Submit
</button>
</form>
);
}
}


TestComponent.test.js



describe("TestComponent tests", () => {
it("`handleSubmit` is called when form is submitted", () => {
const wrapper = shallow(<TestComponent />);
const spy = jest.spyOn(wrapper.instance(), "handleSubmit");

wrapper.find("form").simulate("submit");

expect(spy).toHaveBeenCalled();
});
});


If I do a console.log on the wrapper.instance().handleSubmit I can clearly see that the spy has been injected into the object's property, yet my test still fails stating that the spy was not called.



A CodeSandbox with a working example can be found here: https://codesandbox.io/s/3ymkp3w5x1



Thanks!










share|improve this question
























  • I'm guessing this is due to the fact that the onSubmit function is somehow getting called asynchronously -- going to do some more research in this area.
    – slashp
    Nov 20 '18 at 21:54
















1














I am trying to determine why exactly my Jest spy isn't being called when I can see that the spy is properly "injected" into my component? Here's my very simple example:



TestComponent.js



export default class TestComponent extends Component {
constructor(props) {
super(props);

this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
event && event.preventDefault();
console.log("handleSubmit called!");
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<button className="submit-button" type="submit">
Submit
</button>
</form>
);
}
}


TestComponent.test.js



describe("TestComponent tests", () => {
it("`handleSubmit` is called when form is submitted", () => {
const wrapper = shallow(<TestComponent />);
const spy = jest.spyOn(wrapper.instance(), "handleSubmit");

wrapper.find("form").simulate("submit");

expect(spy).toHaveBeenCalled();
});
});


If I do a console.log on the wrapper.instance().handleSubmit I can clearly see that the spy has been injected into the object's property, yet my test still fails stating that the spy was not called.



A CodeSandbox with a working example can be found here: https://codesandbox.io/s/3ymkp3w5x1



Thanks!










share|improve this question
























  • I'm guessing this is due to the fact that the onSubmit function is somehow getting called asynchronously -- going to do some more research in this area.
    – slashp
    Nov 20 '18 at 21:54














1












1








1







I am trying to determine why exactly my Jest spy isn't being called when I can see that the spy is properly "injected" into my component? Here's my very simple example:



TestComponent.js



export default class TestComponent extends Component {
constructor(props) {
super(props);

this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
event && event.preventDefault();
console.log("handleSubmit called!");
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<button className="submit-button" type="submit">
Submit
</button>
</form>
);
}
}


TestComponent.test.js



describe("TestComponent tests", () => {
it("`handleSubmit` is called when form is submitted", () => {
const wrapper = shallow(<TestComponent />);
const spy = jest.spyOn(wrapper.instance(), "handleSubmit");

wrapper.find("form").simulate("submit");

expect(spy).toHaveBeenCalled();
});
});


If I do a console.log on the wrapper.instance().handleSubmit I can clearly see that the spy has been injected into the object's property, yet my test still fails stating that the spy was not called.



A CodeSandbox with a working example can be found here: https://codesandbox.io/s/3ymkp3w5x1



Thanks!










share|improve this question















I am trying to determine why exactly my Jest spy isn't being called when I can see that the spy is properly "injected" into my component? Here's my very simple example:



TestComponent.js



export default class TestComponent extends Component {
constructor(props) {
super(props);

this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
event && event.preventDefault();
console.log("handleSubmit called!");
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<button className="submit-button" type="submit">
Submit
</button>
</form>
);
}
}


TestComponent.test.js



describe("TestComponent tests", () => {
it("`handleSubmit` is called when form is submitted", () => {
const wrapper = shallow(<TestComponent />);
const spy = jest.spyOn(wrapper.instance(), "handleSubmit");

wrapper.find("form").simulate("submit");

expect(spy).toHaveBeenCalled();
});
});


If I do a console.log on the wrapper.instance().handleSubmit I can clearly see that the spy has been injected into the object's property, yet my test still fails stating that the spy was not called.



A CodeSandbox with a working example can be found here: https://codesandbox.io/s/3ymkp3w5x1



Thanks!







jestjs enzyme






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 21:19









skyboyer

3,33611128




3,33611128










asked Nov 20 '18 at 20:21









slashp

1,70212139




1,70212139












  • I'm guessing this is due to the fact that the onSubmit function is somehow getting called asynchronously -- going to do some more research in this area.
    – slashp
    Nov 20 '18 at 21:54


















  • I'm guessing this is due to the fact that the onSubmit function is somehow getting called asynchronously -- going to do some more research in this area.
    – slashp
    Nov 20 '18 at 21:54
















I'm guessing this is due to the fact that the onSubmit function is somehow getting called asynchronously -- going to do some more research in this area.
– slashp
Nov 20 '18 at 21:54




I'm guessing this is due to the fact that the onSubmit function is somehow getting called asynchronously -- going to do some more research in this area.
– slashp
Nov 20 '18 at 21:54












1 Answer
1






active

oldest

votes


















0














Best practice is not to test that handleSubmit was called, but just to check for the results of calling handleSubmit. Having said that...





Issue



onSubmit is bound directly to the value of this.handleSubmit at the time the component renders.





Solution



Use a lambda function (note, this might cause performance issues) so that onSubmit calls the current value of this.handleSubmit when it is invoked:



<form onSubmit={() => this.handleSubmit()}>





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400938%2fwhy-isnt-my-jest-spy-showing-as-called-when-i-can-see-that-it-is%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Best practice is not to test that handleSubmit was called, but just to check for the results of calling handleSubmit. Having said that...





    Issue



    onSubmit is bound directly to the value of this.handleSubmit at the time the component renders.





    Solution



    Use a lambda function (note, this might cause performance issues) so that onSubmit calls the current value of this.handleSubmit when it is invoked:



    <form onSubmit={() => this.handleSubmit()}>





    share|improve this answer


























      0














      Best practice is not to test that handleSubmit was called, but just to check for the results of calling handleSubmit. Having said that...





      Issue



      onSubmit is bound directly to the value of this.handleSubmit at the time the component renders.





      Solution



      Use a lambda function (note, this might cause performance issues) so that onSubmit calls the current value of this.handleSubmit when it is invoked:



      <form onSubmit={() => this.handleSubmit()}>





      share|improve this answer
























        0












        0








        0






        Best practice is not to test that handleSubmit was called, but just to check for the results of calling handleSubmit. Having said that...





        Issue



        onSubmit is bound directly to the value of this.handleSubmit at the time the component renders.





        Solution



        Use a lambda function (note, this might cause performance issues) so that onSubmit calls the current value of this.handleSubmit when it is invoked:



        <form onSubmit={() => this.handleSubmit()}>





        share|improve this answer












        Best practice is not to test that handleSubmit was called, but just to check for the results of calling handleSubmit. Having said that...





        Issue



        onSubmit is bound directly to the value of this.handleSubmit at the time the component renders.





        Solution



        Use a lambda function (note, this might cause performance issues) so that onSubmit calls the current value of this.handleSubmit when it is invoked:



        <form onSubmit={() => this.handleSubmit()}>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 3:33









        brian-lives-outdoors

        4,850322




        4,850322






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400938%2fwhy-isnt-my-jest-spy-showing-as-called-when-i-can-see-that-it-is%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin