-
-
Notifications
You must be signed in to change notification settings - Fork 87
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
Mock get/set properties when mocking classes #177
Comments
Hi, thanks for the report. that's the tricky part because not all get / set properties are visible via getOwnPropertyDescriptor, what can be extracted is mocked out of the box. these properties are defined in js constructor like as an option you can try to do next: if you use TS 3.7: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier or to mock them manually. mockServiceHelper.mock(instance, 'hardCodedGet', 'get');
mockServiceHelper.mock(instance, 'dynamicGet', 'get'); |
Thank you for looking into this.
Maybe I'm misunderstanding, but the issue I am experiencing is, when using class Example {
get val() { throw new Error('Not mocked'); }
}
console.log(mockServiceHelper.extractPropertiesFromPrototype(Example.prototype)); // ['val']
const mockExample = MockService(Example);
console.log(mockExample.val); // Throws "Not mocked"
Sorry if my original post was not clear; my issue is not regarding fields , but rather |
Hi @JoshuaEN, please excuse for the delay, might you check if the fix works for you: ng-mocks.zip? |
Hi @satanTime, This fix works perfectly, thank you! |
Hello,
For classes,
MockService
appears to only mock methods, deferring get/set properties to the original class's prototype.At least for my use-case, it would be preferable if get/set properties were also mocked to prevent a unit test from accidentally using the actual implementation of a dependency.
Example of Current + Desired behavior (the test passing is desired):
Example in a runnable project
Thoughts?
From a technical standpoint, this would be my proposed change:
Add (to createMockFromPrototype in mock-service.ts):
I would be happy to submit a PR (with tests) if this change is acceptable.
P.S. I noted a few other places stub both the get and set property, even if only one was originally defined.
By stubbing just the get/set properties that were defined, the mock more accurately represents the original class, which I personally would prefer. That said, I'm happy to follow the other pattern here if is preferred (or update the other places to only mock what was originally there, if desired).
The text was updated successfully, but these errors were encountered: