UNPKG

11.7 kBTypeScriptView Raw
1import * as sinonType from 'sinon';
2import { AnyJson, JsonMap, Optional } from '@salesforce/ts-types';
3import { EventEmitter } from 'events';
4import { ConfigContents } from './config/configStore';
5import { Logger } from './logger';
6import { SfdxError } from './sfdxError';
7import { CometClient, CometSubscription, StreamingExtension } from './status/streamingClient';
8/**
9 * Different parts of the system that are mocked out. They can be restored for
10 * individual tests. Test's stubs should always go on the DEFAULT which is exposed
11 * on the TestContext.
12 */
13export interface SandboxTypes {
14 DEFAULT: any;
15 CRYPTO: any;
16 CONFIG: any;
17 CONNECTION: any;
18}
19/**
20 * Different hooks into {@link ConfigFile} used for testing instead of doing file IO.
21 */
22export interface ConfigStub {
23 /**
24 * readFn A function that controls all aspect of {@link ConfigFile.read}. For example, it won't set the contents
25 * unless explicitly done. Only use this if you know what you are doing. Use retrieveContents
26 * instead.
27 */
28 readFn?: () => Promise<ConfigContents>;
29 /**
30 * A function that controls all aspects of {@link ConfigFile.write}. For example, it won't read the contents unless
31 * explicitly done. Only use this if you know what you are doing. Use updateContents instead.
32 */
33 writeFn?: (contents: AnyJson) => Promise<void>;
34 /**
35 * The contents that are used when @{link ConfigFile.read} unless retrieveContents is set. This will also contain the
36 * new config when @{link ConfigFile.write} is called. This will persist through config instances,
37 * such as {@link Alias.update} and {@link Alias.fetch}.
38 */
39 contents?: ConfigContents;
40 /**
41 * A function to conditionally read based on the config instance. The `this` value will be the config instance.
42 */
43 retrieveContents?: () => Promise<JsonMap>;
44 /**
45 * A function to conditionally set based on the config instance. The `this` value will be the config instance.
46 */
47 updateContents?: () => Promise<JsonMap>;
48}
49/**
50 * Different configuration options when running before each
51 */
52export interface TestContext {
53 /**
54 * The default sandbox is cleared out before each test run.
55 *
56 * **See** [sinon sandbox]{@link http://sinonjs.org/releases/v1.17.7/sandbox/}.
57 */
58 SANDBOX: sinonType.SinonSandbox;
59 /**
60 * An object of different sandboxes. Used when
61 * needing to restore parts of the system for customized testing.
62 */
63 SANDBOXES: SandboxTypes;
64 /**
65 * The test logger that is used when {@link Logger.child} is used anywhere. It uses memory logging.
66 */
67 TEST_LOGGER: Logger;
68 /**
69 * id A unique id for the test run.
70 */
71 id: string;
72 /**
73 * A function that returns unique strings.
74 */
75 uniqid: () => string;
76 /**
77 * An object used in tests that interact with config files.
78 */
79 configStubs: {
80 [configName: string]: Optional<ConfigStub>;
81 AuthInfoConfig?: ConfigStub;
82 Aliases?: ConfigStub;
83 SfdxProjectJson?: ConfigStub;
84 SfdxConfig?: ConfigStub;
85 };
86 /**
87 * A function used when resolving the local path.
88 * @param uid Unique id.
89 */
90 localPathRetriever: (uid: string) => Promise<string>;
91 /**
92 * A function used when resolving the global path.
93 * @param uid Unique id.
94 */
95 globalPathRetriever: (uid: string) => Promise<string>;
96 /**
97 * A function used for resolving paths. Calls localPathRetriever and globalPathRetriever.
98 * @param isGlobal `true` if the config is global.
99 * @param uid user id.
100 */
101 rootPathRetriever: (isGlobal: boolean, uid?: string) => Promise<string>;
102 /**
103 * Used to mock http request to Salesforce.
104 * @param request An HttpRequest.
105 * @param options Additional options.
106 *
107 * **See** {@link Connection.request}
108 */
109 fakeConnectionRequest: (request: AnyJson, options?: AnyJson) => Promise<AnyJson>;
110 /**
111 * Gets a config stub contents by name.
112 * @param name The name of the config.
113 * @param group If the config supports groups.
114 */
115 getConfigStubContents(name: string, group?: string): ConfigContents;
116 /**
117 * Sets a config stub contents by name
118 * @param name The name of the config stub.
119 * @param value The actual stub contents. The Mock data.
120 */
121 setConfigStubContents(name: string, value: ConfigContents): void;
122}
123/**
124 * Instantiate a @salesforce/core test context. This is automatically created by `const $$ = testSetup()`
125 * but is useful if you don't want to have a global stub of @salesforce/core and you want to isolate it to
126 * a single describe.
127 *
128 * **Note:** Call `stubContext` in your beforeEach to have clean stubs of @salesforce/core every test run.
129 *
130 * @example
131 * ```
132 * const $$ = instantiateContext();
133 *
134 * beforeEach(() => {
135 * stubContext($$);
136 * });
137 *
138 * afterEach(() => {
139 * restoreContext($$);
140 * });
141 * ```
142 * @param sinon
143 */
144export declare const instantiateContext: (sinon?: any) => TestContext;
145/**
146 * Stub a @salesforce/core test context. This will mock out logging to a file, config file reading and writing,
147 * local and global path resolution, and http request using connection (soon)*.
148 *
149 * This is automatically stubbed in the global beforeEach created by
150 * `const $$ = testSetup()` but is useful if you don't want to have a global stub of @salesforce/core and you
151 * want to isolate it to a single describe.
152 *
153 * **Note:** Always call `restoreContext` in your afterEach.
154 *
155 * @example
156 * ```
157 * const $$ = instantiateContext();
158 *
159 * beforeEach(() => {
160 * stubContext($$);
161 * });
162 *
163 * afterEach(() => {
164 * restoreContext($$);
165 * });
166 * ```
167 * @param testContext
168 */
169export declare const stubContext: (testContext: TestContext) => void;
170/**
171 * Restore a @salesforce/core test context. This is automatically stubbed in the global beforeEach created by
172 * `const $$ = testSetup()` but is useful if you don't want to have a global stub of @salesforce/core and you
173 * want to isolate it to a single describe.
174 *
175 * @example
176 * ```
177 * const $$ = instantiateContext();
178 *
179 * beforeEach(() => {
180 * stubContext($$);
181 * });
182 *
183 * afterEach(() => {
184 * restoreContext($$);
185 * });
186 * ```
187 * @param testContext
188 */
189export declare const restoreContext: (testContext: TestContext) => void;
190/**
191 * Use to mock out different pieces of sfdx-core to make testing easier. This will mock out
192 * logging to a file, config file reading and writing, local and global path resolution, and
193 * *http request using connection (soon)*.
194 *
195 * **Note:** The testSetup should be outside of the describe. If you need to stub per test, use
196 * `instantiateContext`, `stubContext`, and `restoreContext`.
197 * ```
198 * // In a mocha tests
199 * import testSetup from '@salesforce/core/lib/testSetup';
200 *
201 * const $$ = testSetup();
202 *
203 * describe(() => {
204 * it('test', () => {
205 * // Stub out your own method
206 * $$.SANDBOX.stub(MyClass.prototype, 'myMethod').returnsFake(() => {});
207 *
208 * // Set the contents that is used when aliases are read. Same for all config files.
209 * $$.configStubs.Aliases = { contents: { 'myTestAlias': 'user@company.com' } };
210 *
211 * // Will use the contents set above.
212 * const username = Aliases.fetch('myTestAlias');
213 * expect(username).to.equal('user@company.com');
214 * });
215 * });
216 * ```
217 */
218export declare const testSetup: (sinon?: any) => TestContext;
219/**
220 * A pre-canned error for try/catch testing.
221 *
222 * **See** {@link shouldThrow}
223 */
224export declare const unexpectedResult: SfdxError;
225/**
226 * Use for this testing pattern:
227 * ```
228 * try {
229 * await call()
230 * assert.fail('this should never happen');
231 * } catch (e) {
232 * ...
233 * }
234 *
235 * Just do this
236 *
237 * try {
238 * await shouldThrow(call()); // If this succeeds unexpectedResultError is thrown.
239 * } catch(e) {
240 * ...
241 * }
242 * ```
243 * @param f The async function that is expected to throw.
244 */
245export declare function shouldThrow(f: Promise<unknown>): Promise<never>;
246/**
247 * A helper to determine if a subscription will use callback or errorback.
248 * Enable errback to simulate a subscription failure.
249 */
250export declare enum StreamingMockSubscriptionCall {
251 CALLBACK = 0,
252 ERRORBACK = 1
253}
254/**
255 * Additional subscription options for the StreamingMock.
256 */
257export interface StreamingMockCometSubscriptionOptions {
258 /**
259 * Target URL.
260 */
261 url: string;
262 /**
263 * Simple id to associate with this instance.
264 */
265 id: string;
266 /**
267 * What is the subscription outcome a successful callback or an error?.
268 */
269 subscriptionCall: StreamingMockSubscriptionCall;
270 /**
271 * If it's an error that states what that error should be.
272 */
273 subscriptionErrbackError?: SfdxError;
274 /**
275 * A list of messages to playback for the client. One message per process tick.
276 */
277 messagePlaylist?: JsonMap[];
278}
279/**
280 * Simulates a comet subscription to a streaming channel.
281 */
282export declare class StreamingMockCometSubscription extends EventEmitter implements CometSubscription {
283 static SUBSCRIPTION_COMPLETE: string;
284 static SUBSCRIPTION_FAILED: string;
285 private options;
286 constructor(options: StreamingMockCometSubscriptionOptions);
287 /**
288 * Sets up a streaming subscription callback to occur after the setTimeout event loop phase.
289 * @param callback The function to invoke.
290 */
291 callback(callback: () => void): void;
292 /**
293 * Sets up a streaming subscription errback to occur after the setTimeout event loop phase.
294 * @param callback The function to invoke.
295 */
296 errback(callback: (error: Error) => void): void;
297}
298/**
299 * Simulates a comet client. To the core streaming client this mocks the internal comet impl.
300 * The uses setTimeout(0ms) event loop phase just so the client can simulate actual streaming without the response
301 * latency.
302 */
303export declare class StreamingMockCometClient extends CometClient {
304 private readonly options;
305 /**
306 * Constructor
307 * @param {StreamingMockCometSubscriptionOptions} options Extends the StreamingClient options.
308 */
309 constructor(options: StreamingMockCometSubscriptionOptions);
310 /**
311 * Fake addExtension. Does nothing.
312 */
313 addExtension(extension: StreamingExtension): void;
314 /**
315 * Fake disable. Does nothing.
316 */
317 disable(label: string): void;
318 /**
319 * Fake handshake that invoke callback after the setTimeout event phase.
320 * @param callback The function to invoke.
321 */
322 handshake(callback: () => void): void;
323 /**
324 * Fake setHeader. Does nothing,
325 */
326 setHeader(name: string, value: string): void;
327 /**
328 * Fake subscription that completed after the setTimout event phase.
329 * @param channel The streaming channel.
330 * @param callback The function to invoke after the subscription completes.
331 */
332 subscribe(channel: string, callback: (message: JsonMap) => void): CometSubscription;
333 /**
334 * Fake disconnect. Does Nothing.
335 */
336 disconnect(): Promise<void>;
337}
338/**
339 * Mock class for OrgData.
340 */
341export declare class MockTestOrgData {
342 testId: string;
343 alias?: string;
344 username: string;
345 devHubUsername?: string;
346 orgId: string;
347 loginUrl: string;
348 instanceUrl: string;
349 clientId: string;
350 clientSecret: string;
351 authcode: string;
352 accessToken: string;
353 refreshToken: string;
354 userId: string;
355 redirectUri: string;
356 constructor(id?: string);
357 createDevHubUsername(username: string): void;
358 makeDevHub(): void;
359 createUser(user: string): MockTestOrgData;
360 getMockUserInfo(): JsonMap;
361 getConfig(): Promise<ConfigContents>;
362}