1 | import _ from './wrap/lodash'
|
2 | import callback from './callback'
|
3 | import isCallback from './matchers/is-callback'
|
4 | import calls from './store/calls'
|
5 | import log from './log'
|
6 | import stubbings from './store/stubbings'
|
7 | import tdConfig from './config'
|
8 |
|
9 | export 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 |
|
34 | function 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 |
|
42 | function ensureRehearsalOccurred (last) {
|
43 | if (!last) {
|
44 | return log.error('td.when', `\
|
45 | No test double invocation call detected for \`when()\`.
|
46 |
|
47 | Usage:
|
48 | when(myTestDouble('foo')).thenReturn('bar')\
|
49 | `
|
50 | )
|
51 | }
|
52 | }
|
53 |
|
54 | function 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 |
|
64 | function warnIfPromiseless () {
|
65 | if (tdConfig().promiseConstructor == null) {
|
66 | log.warn('td.when', `\
|
67 | no promise constructor is set, so this \`thenResolve\` or \`thenReject\` stubbing
|
68 | will fail if it's satisfied by an invocation on the test double. You can tell
|
69 | testdouble.js which promise constructor to use with \`td.config\`, like so:
|
70 |
|
71 | td.config({
|
72 | promiseConstructor: require('bluebird')
|
73 | })\
|
74 | `)
|
75 | }
|
76 | }
|