Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error when stubbing a property that does not exist #2629

Open
DanKaplanSES opened this issue Nov 27, 2024 · 2 comments
Open

Error when stubbing a property that does not exist #2629

DanKaplanSES opened this issue Nov 27, 2024 · 2 comments

Comments

@DanKaplanSES
Copy link
Contributor

I'd like a more informative error message for this situation:

        const x = {
            getFoo: () => {
                return "bar"
            }
        }

        sinon.stub(x, 'getFoo').value("baz");

        console.log(x.getFoo()); // TypeError: x.getFoo is not a function
        console.log(typeof x.getFoo); // string

The intent here was to stub x's getFoo method, but the user mistakenly used value to do so. In this situation, it would be more helpful for sinon to error on the stub line with an error message similar to: "x.getFoo is a function, not a getter. Use returns instead of value."

I'm aware this is a breaking change, so I think the user would need to configure some sort of "strict mode" to enable an error message like this.

@DanKaplanSES DanKaplanSES changed the title Error when stubbing a property/function that does not exist Error when stubbing a property that does not exist Nov 27, 2024
@senocular
Copy link

A property being a function doesn't mean it should always be a function. It may be desirable to replace the function entirely rather than what that function returns.

Consider something like the HTMLElement.prototype.onclick callback. This is a function property that can be a function or null. As a function the function is called when the respective element is clicked. When null, no call is made. You may need to test for situations where that property is null meaning changing its value from a function to null, not changing what the function returns. Granted this property normally starts out as null, but this is just an example (you might imagine someone creating a web component that defines a default onclick which could later be set to null).

@DanKaplanSES
Copy link
Contributor Author

DanKaplanSES commented Mar 8, 2025

@senocular That's a good point. Perhaps the error message should stay where it is (console.log(x.getFoo());), but it should be enhanced to provide this information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants