serverless-mocha-plugin
serverless-mocha-plugin copied to clipboard
Testing with invoke local?
Very interested in the approach here - and learning from your experience... I currently use mocha to test my handlers directly and that seems to work well (e.g. https://github.com/activescott/sheetmonkey-server/blob/master/server/test/tests/PluginsHandler.js). The approach in this plugin is one step closer to production since it more closely emulates invocation via lambda. However, the thing I find myself frequently overlooking with my current testing isn't covered by the approach in this plugin.
The tests I have now do not validate that I have my serverless.yml in sync with the code itself. I was thinking of doing this by having the mocha tests use serverless invoke local
to test the http event bindings in addition to the code itself. Just curious if you have thought about this more than I have and rule it out - maybe I'm missing something?
@activescott you could actually achieve that by just defining your own test template, which uses serverless invoke local (e.g. using execSync) for running the actual tests (e.g using sls invoke test). See "Using own template for a test file" in the documentation. When you've defined your own template, that will be used with "sls create test" and "sls create function". (The default template can be seen here: https://github.com/SC5/serverless-mocha-plugin/blob/master/templates/test-template.ejs )
@mpuittinen Thanks. Makes sense. I'm going to give this more thought. This is all on the right track, but the more I think about this, I'm thinking maybe the best approach is a test helper that will enable running tests based on the http events defined in serverless.yml. So maybe I can write a mocha tests that would look something like this:
it('should return info about the current user', function() {
let result = slsInvoke('GET api/users/me')
expect(result).to.eventually.not.be.empty
})
Here slsInvoke
would invoke the appropriate function via sls invoke local
but it will determine the appropriate function by finding the corresponding http event binding in serverless.yml.
The thing I like about this that the other approaches leave out (including how I described it above) is that it not only tests the function handler (of which this plugin and direct testing based on the handler offers), but it also confirms that the http events are configured properly in serverless.yml.
Something like this: https://github.com/activescott/serverless-http-invoker :)
@activescott that looks cool. Will check how to have that integrated into the mocha-plugin. e.g something like
httpWrapped = mochaPlugin.getHttpWrapper() ... httpWrapped.invoke('POST /path/to/resource', { payload })
The point of having a wrapper would be to support also the --live option (i.e. calling the actual deployed API Gateway endpoints)