Created
May 20, 2017 05:52
-
-
Save SunKing2/cc343edababfa5abbb6c0a9c9babd373 to your computer and use it in GitHub Desktop.
Testing Javascript with standalone jasmine
This file contains 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
If this link doesn't work, go to next step: | |
https://github.com/jasmine/jasmine/releases | |
download latest version of standalone jasmine from that link or search Google for "standalone jasmine". | |
Follow this tutorial: | |
https://code.tutsplus.com/tutorials/testing-your-javascript-with-jasmine--net-21229 | |
Here's my version of the code: | |
// src/convert.js | |
function Convert(iAmount, sUnitFrom) { | |
if (!['in', 'cm', 'litres', 'usgallons'].includes(sUnitFrom)) { | |
throw new Error('invalid from unit') | |
} | |
let conv = { | |
cm: 2.54, | |
yards: 0.0109361, | |
usgallons: 0.264172, | |
cups: 16 | |
} | |
return { | |
to: function(sUnitTo) { | |
if (typeof conv[sUnitTo] === 'undefined') { | |
throw new Error('invalid to unit') | |
} | |
return iAmount * conv[sUnitTo] | |
} | |
} | |
} | |
// spec/convertSpec.js | |
/* global describe */ | |
/* global it */ | |
/* global expect */ | |
/* global Convert */ | |
describe('Convert library', function() { | |
let expected = -1 | |
let actual = -1 | |
describe('distance converter', function() { | |
it('converts inches to cm', function() { | |
actual = Convert(12, 'in').to('cm') | |
expected = 30.48 | |
expect(actual).toEqual(expected) | |
actual = Convert(1, 'in').to('cm') | |
expected = 2.54 | |
expect(actual).toEqual(expected) | |
}) | |
it('converts cm to yards', function(){ | |
actual = Convert(2000, 'cm').to('yards') | |
expected = 21.87 | |
expect(actual).toBeCloseTo(expected, 2) | |
}) | |
}) | |
describe('volume converter', function() { | |
it('converts litres to usgallons', function() { | |
actual = Convert(3, 'litres').to('usgallons') | |
expected = 0.79 | |
expect(actual).toBeCloseTo(expected, 2) | |
}) | |
it('converts usgallons to cups', function() { | |
actual = Convert(2, 'usgallons').to('cups') | |
expected = 32 | |
expect(actual).toEqual(expected) | |
}) | |
}) | |
it('throws an error with invalid from unit', function() { | |
expect( | |
function() { | |
Convert(1, 'dollar').to('yens') | |
} | |
).toThrow(new Error('invalid from unit')) | |
}) | |
it('throws an error with invalid to unit', function() { | |
expect( | |
function() { | |
Convert(1, 'cm').to('furlongs') | |
} | |
).toThrow(new Error('invalid to unit')) | |
}) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment