diff --git a/README.md b/README.md index 226e02f..03e1865 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,36 @@ describe('/products', function() { }); ``` +### call remote only once + +By default `whenCalledRemotely` will be run before each `it()`. This can be changed to run only once by adding a `$once` as a param to the callback function (i.e. `lt.describe.whenCalledRemotely('GET', '/', function($once) {..})`) + + +```js +var lt = require('loopback-testing'); +var assert = require('assert'); +var app = require('../server/server.js'); //path to app.js or server.js + +describe('/products', function() { + lt.beforeEach.withApp(app); + lt.describe.whenCalledRemotely('POST', '/products', { + name: 'product-1' + }, function($once) { + + var id; + + it('should have statusCode 200', function() { + id = this.res.body.id; + assert.equal(this.res.statusCode, 200); + }); + + it('should have only been called once', function() { + assert.equal(this.res.body.id, id); + }); + }); +}); +``` + ## building test data Use TestDataBuilder to build many Model instances in one async call. Specify diff --git a/lib/helpers.js b/lib/helpers.js index 994edcd..d5b78be 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -240,8 +240,18 @@ _describe.whenCalledRemotely = function(verb, url, data, cb) { urlStr = '/'; } + var once = cb.toString().match(/^function \([^\)]*\$once[^\)]*\)/) ? false : null; + describe(verb.toUpperCase() + ' ' + urlStr, function() { beforeEach(function(cb) { + if(once !== null) { + if(once === true) { + cb(); + return; + } + once = true; + } + if(typeof url === 'function') { this.url = url.call(this); } diff --git a/test/test.js b/test/test.js index 70b4448..e479526 100644 --- a/test/test.js +++ b/test/test.js @@ -67,9 +67,18 @@ describe('helpers', function () { helpers.describe.staticMethod('create', function() { helpers.beforeEach.withArgs({foo: 'bar'}); helpers.describe.whenCalledRemotely('POST', '/xxx-test-models', function() { + + var id; + it('should call the method over rest', function () { + id = this.res.body.id; assert.equal(this.res.statusCode, 200); }); + + it('should be called again have new id', function () { + assert.notEqual(this.res.body.id, id); + }); + }); }); helpers.describe.staticMethod('findById', function() { @@ -109,4 +118,25 @@ describe('helpers', function () { }); }); }); + + describe('whenCalledRemotely once', function() { + helpers.describe.staticMethod('create', function() { + helpers.beforeEach.withArgs({foo: 'bar'}); + helpers.describe.whenCalledRemotely('POST', '/xxx-test-models', function($once) { + + var id; + + it('should call the method over rest', function () { + id = this.res.body.id; + assert.equal(this.res.statusCode, 200); + }); + + it('should have only been called once', function () { + assert.equal(this.res.body.id, id); + }); + + }); + }); + }); + });