1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const lodash_1 = require("./wrap/lodash");
|
4 | const callback_1 = require("./callback");
|
5 | const is_callback_1 = require("./matchers/is-callback");
|
6 | const calls_1 = require("./store/calls");
|
7 | const log_1 = require("./log");
|
8 | const stubbings_1 = require("./store/stubbings");
|
9 | const config_1 = require("./config");
|
10 | function when(__userDoesRehearsalInvocationHere__, config = {}) {
|
11 | return ({
|
12 | thenReturn(...stubbedValues) {
|
13 | return addStubbing(stubbedValues, config, 'thenReturn');
|
14 | },
|
15 | thenCallback(...stubbedValues) {
|
16 | return addStubbing(stubbedValues, config, 'thenCallback');
|
17 | },
|
18 | thenDo(...stubbedValues) {
|
19 | return addStubbing(stubbedValues, config, 'thenDo');
|
20 | },
|
21 | thenThrow(...stubbedValues) {
|
22 | return addStubbing(stubbedValues, config, 'thenThrow');
|
23 | },
|
24 | thenResolve(...stubbedValues) {
|
25 | warnIfPromiseless();
|
26 | return addStubbing(stubbedValues, config, 'thenResolve');
|
27 | },
|
28 | thenReject(...stubbedValues) {
|
29 | warnIfPromiseless();
|
30 | return addStubbing(stubbedValues, config, 'thenReject');
|
31 | }
|
32 | });
|
33 | }
|
34 | exports.default = when;
|
35 | function addStubbing(stubbedValues, config, plan) {
|
36 | const last = calls_1.default.pop();
|
37 | ensureRehearsalOccurred(last);
|
38 | lodash_1.default.assign(config, { plan });
|
39 | stubbings_1.default.add(last.testDouble, concatImpliedCallback(last.args, config), stubbedValues, config);
|
40 | return last.testDouble;
|
41 | }
|
42 | function ensureRehearsalOccurred(last) {
|
43 | if (!last) {
|
44 | return log_1.default.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 | function concatImpliedCallback(args, config) {
|
53 | if (config.plan !== 'thenCallback') {
|
54 | return args;
|
55 | }
|
56 | else if (!lodash_1.default.some(args, is_callback_1.default)) {
|
57 | return args.concat(callback_1.default);
|
58 | }
|
59 | else {
|
60 | return args;
|
61 | }
|
62 | }
|
63 | function warnIfPromiseless() {
|
64 | if (config_1.default().promiseConstructor == null) {
|
65 | log_1.default.warn('td.when', `\
|
66 | no promise constructor is set, so this \`thenResolve\` or \`thenReject\` stubbing
|
67 | will fail if it's satisfied by an invocation on the test double. You can tell
|
68 | testdouble.js which promise constructor to use with \`td.config\`, like so:
|
69 |
|
70 | td.config({
|
71 | promiseConstructor: require('bluebird')
|
72 | })\
|
73 | `);
|
74 | }
|
75 | }
|