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

Fix the class context validation #43

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,12 @@ function debounce(function_, wait = 100, options = {}) {
}

const debounced = function (...arguments_) {
if (storedContext && this !== storedContext) {
throw new Error('Debounced method called with different contexts.');
if (
storedContext
&& this !== storedContext
&& Object.getPrototypeOf(this) === Object.getPrototypeOf(storedContext)
) {
throw new Error('Debounced method called with different contexts of the same prototype.');
}

storedContext = this; // eslint-disable-line unicorn/no-this-assignment
Expand Down
33 changes: 25 additions & 8 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ test('forcing execution', async t => {
});

test('context check in debounced function', async t => {
await t.test('should throw an error if debounced method is called with different contexts', async () => {
await t.test('should throw an error if debounced method is called with different contexts of the same class', async () => {
function MyClass() {}

MyClass.prototype.debounced = debounce(() => {});
Expand All @@ -157,15 +157,32 @@ test('context check in debounced function', async t => {

instance1.debounced();

let errorThrown = false;
try {
assert.throws(() => {
instance2.debounced();
} catch (error) {
errorThrown = true;
assert.strictEqual(error.message, 'Debounced method called with different contexts.', 'Error message should match');
}
}, {
message: 'Debounced method called with different contexts of the same prototype.',
}, 'An error should have been thrown');
});

await t.test('should not throw an error if debounced method is called with different contexts of different classes', async () => {
function MyClass1() {}
function MyClass2() {}

const debouncedFunction = debounce(() => {});

MyClass1.prototype.debounced = debouncedFunction;
MyClass2.prototype.debounced = debouncedFunction;

assert.ok(errorThrown, 'An error should have been thrown');
const instance1 = new MyClass1();
const instance2 = new MyClass2();

instance1.debounced();

assert.doesNotThrow(() => {
instance2.debounced();
}, {
message: 'Debounced method called with different contexts of the same prototype.',
}, 'An error should not have been thrown');
});
});

Expand Down