Last active
February 22, 2018 20:52
-
-
Save nerdcave/4418ca2c787f28c6cb30b7c96d7af1fe to your computer and use it in GitHub Desktop.
JavaScript testing with lazy loading/evaluation (like Rspec let)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Uses Jasmine's `this` feature: | |
// https://jasmine.github.io/2.9/introduction#section-The_<code>this</code>_keyword | |
// Example without lazy evaluation: | |
const sum = (a, b) => a + b; | |
describe('No lazy eval :(', () => { | |
let a, b, total; | |
beforeEach(() => { | |
a = 5; | |
b = 3; | |
total = sum(a, b); // bleh | |
}); | |
it('sums', () => { | |
expect(total).toEqual(8); | |
}); | |
it('sums with b changed', () => { | |
b = 5; | |
total = sum(a, b); // boo | |
expect(total).toEqual(10); | |
}); | |
it('sums with both changed', () => { | |
a = 10; | |
b = 8; | |
total = sum(a, b); // hiss | |
expect(total).toEqual(18); | |
}); | |
}); | |
// WITH lazy evaluation: | |
// This can go in a test_helper file and be imported. | |
// Note: beforeEach() must use function() {} and not () => {} | |
beforeEach(function() { | |
this.$lazy = (propName, getter) => { | |
let lazy; | |
Object.defineProperty(this, propName, { | |
get() { | |
lazy = lazy || getter.call(this); | |
return lazy; | |
}, | |
set() {}, | |
enumerable: true, | |
configurable: true, | |
}); | |
}; | |
}); | |
const sum = (a, b) => a + b; | |
// beforeEach() and it() must use function() {} syntax | |
describe('Lazy eval! :D', () => { | |
beforeEach(function() { | |
this.a = 5; | |
this.b = 3; | |
this.$lazy('total', () => sum(this.a, this.b)); | |
}); | |
it('sums', function() { | |
expect(this.total).toEqual(8); | |
}); | |
it('sums with b changed', function() { | |
this.b = 5; | |
expect(this.total).toEqual(10); | |
}); | |
it('sums with both changed', function() { | |
this.a = 10; | |
this.b = 8; | |
expect(this.total).toEqual(18); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment