-
Notifications
You must be signed in to change notification settings - Fork 55
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
Unable to mock getter #29
Comments
Although it would be better to integrate support for getters into the library, it is possible to mock a getter whilst using interface Strings {
readonly size: number;
item(index: number): string;
} Just creating a mock for this interface using However it is possible to define a property that uses a getter function directly on the implementation object that // Construct the mockers
const baseMock = {};
const mockStrings = mock<Strings>(baseMock);
const mockSizeGetter = jest.fn<number, []>();
Object.defineProperty(baseMock, 'size', { get: mockSizeGetter }); This code creates an object Now we can prepare the mockers to pretend to be a collection of three strings. mockSizeGetter.mockReturnValue(3);
mockStrings.item
.mockReturnValueOnce('zero')
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'); The following code demonstrates that the getter have been mocked. const concatenate = (strings: Strings): string => {
let result = '';
for (let i = 0; i < strings.size; ++i) {
if (i > 0) {
result += ',';
}
result += strings.item(i);
}
return result;
}
expect(concatenate(mockStrings)).toEqual('zero,one,two'); |
Thanks for this example. While I am not working with any projects that are using jest framework at the moment, I will give it a try in the future. =) |
Is it possible to mock getters?
I always get the error
Cannot assign to 'xyz' because it is a read-only property
The text was updated successfully, but these errors were encountered: