I already do things like this in my tests, so I think it is a good idea. Jasmine is
pretty lightweight though, so I'm not sure this kind of thing belongs in
it. It doesn't feel orthogonal to the rest of the library. However, I'm
all in favor of adding more stuff to jasmine (rspec style "let"
declarations, for example, would be an amazing feature).
Of course, I have no say at all. Nice code.
JP <
jph...@gmail.com> writes:
> Hi,I've lately started to use a pattern to DRY up my Jasmine tests. I call this pattern "Data Provider" (I copied the feature name from PHPUnit, which is were I first learned about it). The basic premise of a data provider is to feed a test with multiple test values to avoid repeating your test code over and over. Imagine you have a validation test for a username that looks like this:describe("username validation", function() { it("should return true for valid usernames", function() { expect(validateUserName("abc")).toBeTruthy(); expect(validateUserName("longusername")).toBeTruthy(); expect(validateUserName("john_doe")).toBeTruthy(); }) it("should return false for invalid usernames", function() { expect(validateUserName("ab")).toBeFalsy(); expect(validateUserName("name_too_long")).toBeFalsy(); expect(validateUserName("no spaces")).toBeFalsy(); expect(validateUserName("inv*alid")).toBeFalsy(); })})I don't really like to repeat many expectations within one test block. With the data provider pattern it would look like this:describe("username validation", function() { using("valid values", ["abc", "longusername", "john_doe"], function(value){ it("should return true for valid usernames", function() { expect(validateUserName(value)).toBeTruthy(); }) }) using("invalid values", ["ab", "name_too_long", "no spaces", "inv*alid"], function(value){ it("should return false for invalid usernames", function() { expect(validateUserName(value)).toBeFalsy(); }) })})I implemented a very simple function called "using" that can work with Jasmine out of the box:<span style="font-family: 'courier new', monospace; ">function using(name, values, func){</span> for (var i = 0, count = values.length; i < count; i++) { if (Object.prototype.toString.call(values[i]) !== '[object Array]') { values[i] = [values[i]]; } func.apply(this, values[i]); jasmine.currentEnv_.currentSpec.description += ' (with "' + name + '" using ' + values[i].join(', ') + ')'; }}You can see the attachments for additional examples and you can also check out a demo at
http://jphpsf.com/jasmine-data-provider/What do you guys think of this pattern? I've searched for an existing solution but could not find one. Do you think this would be a good addition to Jasmine itself? I'll be happy to work on a pull request :)Cheers!JP