UNPKG

2.54 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");
10function 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}
34exports.default = when;
35function 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}
42function ensureRehearsalOccurred(last) {
43 if (!last) {
44 return log_1.default.error('td.when', `\
45No test double invocation call detected for \`when()\`.
46
47 Usage:
48 when(myTestDouble('foo')).thenReturn('bar')\
49`);
50 }
51}
52function 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}
63function warnIfPromiseless() {
64 if (config_1.default().promiseConstructor == null) {
65 log_1.default.warn('td.when', `\
66no promise constructor is set, so this \`thenResolve\` or \`thenReject\` stubbing
67will fail if it's satisfied by an invocation on the test double. You can tell
68testdouble.js which promise constructor to use with \`td.config\`, like so:
69
70 td.config({
71 promiseConstructor: require('bluebird')
72 })\
73`);
74 }
75}