Files
cypress/packages/server/lib/task.coffee
Chris Breiding d1fe365eca Add cy.task() command (#1422)
* server: handle undefined values from plugins

* server: have plugins process inherit stdio

so console.logs and such from plugins file come through

* add cy.task()

* server: fix config spec

* driver: fix task spec

* server: change ‘task’ to ‘task:requested’

* server: have ‘task’ event take object literal instead of function

* server: document how to run individual integration and e2e tests

* fix cy.task specs

* server: fix task e2e spec

* ensure stack trace comes through for task error

* don’t show stack for ‘known’ user errors

* add types for cy.task

* @sandbox -> sinon

* add e2e spec for task returning undefined

* update readme re: e2e —spec

* timedout -> timedOut

* new Promise + setTimeout -> Promise.delay

* improve cy.task() error messages

* fix specs
2018-05-15 20:49:20 -04:00

47 lines
1.8 KiB
CoffeeScript

_ = require("lodash")
Promise = require("bluebird")
debug = require("debug")("cypress:server:task")
plugins = require("./plugins")
docsUrl = "https://on.cypress.io/api/task"
throwKnownError = (message, props = {}) ->
err = new Error(message)
_.extend(err, props, { isKnownError: true })
throw err
module.exports = {
run: (pluginsFilePath, options) ->
debug("run task", options.task, "with arg", options.arg)
fileAndDocsUrl = "\n\nFix this in your plugins file here:\n#{pluginsFilePath}\n\n#{docsUrl}"
Promise
.try ->
if not plugins.has("task")
debug("'task' event is not registered")
throwKnownError("The 'task' event has not been registered in the plugins file. You must register it before using cy.task()#{fileAndDocsUrl}")
plugins.execute("task", options.task, options.arg)
.then (result) ->
if result is "__cypress_unhandled__"
debug("task is unhandled")
return plugins.execute("_get:task:keys").then (keys) ->
throwKnownError("The task '#{options.task}' was not handled in the plugins file. The following tasks are registered: #{keys.join(", ")}#{fileAndDocsUrl}")
if result is undefined
debug("result is undefined")
return plugins.execute("_get:task:body", options.task).then (body) ->
throwKnownError("The task '#{options.task}' returned undefined. You must return a promise, a value, or null to indicate that the task was handled.\n\nThe task handler was:\n\n#{body}#{fileAndDocsUrl}")
debug("result is:", result)
return result
.timeout(options.timeout)
.catch Promise.TimeoutError, ->
debug("timed out after #{options.timeout}ms")
plugins.execute("_get:task:body", options.task).then (body) ->
err = new Error("The task handler was:\n\n#{body}#{fileAndDocsUrl}")
err.timedOut = true
throw err
}