3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const lodash_1 = require("./wrap/lodash");
4const callback_1 = require("./callback");
5const is_callback_1 = require("./matchers/is-callback");
6const calls_1 = require("./store/calls");
7const log_1 = require("./log");
8const stubbings_1 = require("./store/stubbings");
9const config_1 = require("./config");
10const clone_deep_if_possible_1 = require("./clone-deep-if-possible");
11const symbols_1 = require("./symbols");
12function when(__userDoesRehearsalInvocationHere__, config = {}) {
13 return ({
14 thenReturn(...stubbedValues) {
15 return addStubbing(stubbedValues, config, 'thenReturn');
16 },
17 thenCallback(...stubbedValues) {
18 return addStubbing(stubbedValues, config, 'thenCallback');
19 },
20 thenDo(...stubbedValues) {
21 return addStubbing(stubbedValues, config, 'thenDo');
22 },
23 thenThrow(...stubbedValues) {
24 return addStubbing(stubbedValues, config, 'thenThrow');
25 },
26 thenResolve(...stubbedValues) {
27 warnIfPromiseless();
28 return addStubbing(stubbedValues, config, 'thenResolve');
29 },
30 thenReject(...stubbedValues) {
31 warnIfPromiseless();
32 return addStubbing(stubbedValues, config, 'thenReject');
33 }
34 });
35}
36exports.default = when;
37function addStubbing(stubbedValues, config, plan) {
38 const last = calls_1.default.pop();
39 ensureRehearsalOccurred(last);
40 ensureCloneableIfCloneArgs(last, config);
41 lodash_1.default.assign(config, { plan });
42 stubbings_1.default.add(last.testDouble, concatImpliedCallback(last.args, config), stubbedValues, config);
43 return last.testDouble;
44}
45function ensureRehearsalOccurred(last) {
46 if (!last) {
47 return log_1.default.error('td.when', `\
48No test double invocation call detected for \`when()\`.
49
50 Usage:
51 when(myTestDouble('foo')).thenReturn('bar')\
52`);
53 }
54}
55function ensureCloneableIfCloneArgs(last, config) {
56 if (config.cloneArgs && (0, clone_deep_if_possible_1.default)(last.args) === symbols_1.default.uncloneable) {
57 return log_1.default.error('td.when', `\
58Failed to deep-clone arguments. Ensure lodash _.cloneDeep works on them
59`);
60 }
61}
62function concatImpliedCallback(args, config) {
63 if (config.plan !== 'thenCallback') {
64 return args;
65 }
66 else if (!lodash_1.default.some(args, is_callback_1.default)) {
67 return args.concat(callback_1.default);
68 }
69 else {
70 return args;
71 }
72}
73function warnIfPromiseless() {
74 if ((0, config_1.default)().promiseConstructor == null) {
75 log_1.default.warn('td.when', `\
76no promise constructor is set, so this \`thenResolve\` or \`thenReject\` stubbing
77will fail if it's satisfied by an invocation on the test double. You can tell
78testdouble.js which promise constructor to use with \`td.config\`, like so:
79
80 td.config({
81 promiseConstructor: require('bluebird')
82 })\
83`);
84 }
85}