UNPKG

2.14 kBJavaScriptView Raw
1import _ from './wrap/lodash'
2import callback from './callback'
3import isCallback from './matchers/is-callback'
4import calls from './store/calls'
5import log from './log'
6import stubbings from './store/stubbings'
7import tdConfig from './config'
8
9export default function when (__userDoesRehearsalInvocationHere__, config = {}) {
10 return ({
11 thenReturn (...stubbedValues) {
12 return addStubbing(stubbedValues, config, 'thenReturn')
13 },
14 thenCallback (...stubbedValues) {
15 return addStubbing(stubbedValues, config, 'thenCallback')
16 },
17 thenDo (...stubbedValues) {
18 return addStubbing(stubbedValues, config, 'thenDo')
19 },
20 thenThrow (...stubbedValues) {
21 return addStubbing(stubbedValues, config, 'thenThrow')
22 },
23 thenResolve (...stubbedValues) {
24 warnIfPromiseless()
25 return addStubbing(stubbedValues, config, 'thenResolve')
26 },
27 thenReject (...stubbedValues) {
28 warnIfPromiseless()
29 return addStubbing(stubbedValues, config, 'thenReject')
30 }
31 })
32}
33
34function addStubbing (stubbedValues, config, plan) {
35 const last = calls.pop()
36 ensureRehearsalOccurred(last)
37 _.assign(config, { plan })
38 stubbings.add(last.testDouble, concatImpliedCallback(last.args, config), stubbedValues, config)
39 return last.testDouble
40}
41
42function ensureRehearsalOccurred (last) {
43 if (!last) {
44 return log.error('td.when', `\
45No test double invocation call detected for \`when()\`.
46
47 Usage:
48 when(myTestDouble('foo')).thenReturn('bar')\
49`
50 )
51 }
52}
53
54function concatImpliedCallback (args, config) {
55 if (config.plan !== 'thenCallback') {
56 return args
57 } else if (!_.some(args, isCallback)) {
58 return args.concat(callback)
59 } else {
60 return args
61 }
62}
63
64function warnIfPromiseless () {
65 if (tdConfig().promiseConstructor == null) {
66 log.warn('td.when', `\
67no promise constructor is set, so this \`thenResolve\` or \`thenReject\` stubbing
68will fail if it's satisfied by an invocation on the test double. You can tell
69testdouble.js which promise constructor to use with \`td.config\`, like so:
70
71 td.config({
72 promiseConstructor: require('bluebird')
73 })\
74`)
75 }
76}