@metamask/snaps-jest 0.35.1-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +587 -0
- package/dist/cjs/environment.js +205 -0
- package/dist/cjs/environment.js.map +1 -0
- package/dist/cjs/helpers.js +67 -0
- package/dist/cjs/helpers.js.map +1 -0
- package/dist/cjs/index.js +42 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/internals/environment.js +19 -0
- package/dist/cjs/internals/environment.js.map +1 -0
- package/dist/cjs/internals/index.js +28 -0
- package/dist/cjs/internals/index.js.map +1 -0
- package/dist/cjs/internals/interface.js +103 -0
- package/dist/cjs/internals/interface.js.map +1 -0
- package/dist/cjs/internals/logger.js +14 -0
- package/dist/cjs/internals/logger.js.map +1 -0
- package/dist/cjs/internals/network.js +146 -0
- package/dist/cjs/internals/network.js.map +1 -0
- package/dist/cjs/internals/request.js +121 -0
- package/dist/cjs/internals/request.js.map +1 -0
- package/dist/cjs/internals/server.js +75 -0
- package/dist/cjs/internals/server.js.map +1 -0
- package/dist/cjs/internals/structs.js +124 -0
- package/dist/cjs/internals/structs.js.map +1 -0
- package/dist/cjs/internals/types.js +6 -0
- package/dist/cjs/internals/types.js.map +1 -0
- package/dist/cjs/internals/wait-for.js +63 -0
- package/dist/cjs/internals/wait-for.js.map +1 -0
- package/dist/cjs/matchers.js +117 -0
- package/dist/cjs/matchers.js.map +1 -0
- package/dist/cjs/options.js +29 -0
- package/dist/cjs/options.js.map +1 -0
- package/dist/cjs/setup.js +10 -0
- package/dist/cjs/setup.js.map +1 -0
- package/dist/cjs/types.js +13 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/esm/environment.js +182 -0
- package/dist/esm/environment.js.map +1 -0
- package/dist/esm/helpers.js +82 -0
- package/dist/esm/helpers.js.map +1 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/internals/environment.js +14 -0
- package/dist/esm/internals/environment.js.map +1 -0
- package/dist/esm/internals/index.js +12 -0
- package/dist/esm/internals/index.js.map +1 -0
- package/dist/esm/internals/interface.js +100 -0
- package/dist/esm/internals/interface.js.map +1 -0
- package/dist/esm/internals/logger.js +4 -0
- package/dist/esm/internals/logger.js.map +1 -0
- package/dist/esm/internals/network.js +141 -0
- package/dist/esm/internals/network.js.map +1 -0
- package/dist/esm/internals/request.js +120 -0
- package/dist/esm/internals/request.js.map +1 -0
- package/dist/esm/internals/server.js +68 -0
- package/dist/esm/internals/server.js.map +1 -0
- package/dist/esm/internals/structs.js +100 -0
- package/dist/esm/internals/structs.js.map +1 -0
- package/dist/esm/internals/types.js +3 -0
- package/dist/esm/internals/types.js.map +1 -0
- package/dist/esm/internals/wait-for.js +63 -0
- package/dist/esm/internals/wait-for.js.map +1 -0
- package/dist/esm/matchers.js +108 -0
- package/dist/esm/matchers.js.map +1 -0
- package/dist/esm/options.js +26 -0
- package/dist/esm/options.js.map +1 -0
- package/dist/esm/setup.js +6 -0
- package/dist/esm/setup.js.map +1 -0
- package/dist/esm/types.js +3 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/types/environment.d.ts +53 -0
- package/dist/types/helpers.d.ts +28 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/internals/environment.d.ts +7 -0
- package/dist/types/internals/index.d.ts +9 -0
- package/dist/types/internals/interface.d.ts +25 -0
- package/dist/types/internals/logger.d.ts +2 -0
- package/dist/types/internals/network.d.ts +87 -0
- package/dist/types/internals/request.d.ts +58 -0
- package/dist/types/internals/server.d.ts +14 -0
- package/dist/types/internals/structs.d.ts +164 -0
- package/dist/types/internals/types.d.ts +19 -0
- package/dist/types/internals/wait-for.d.ts +38 -0
- package/dist/types/matchers.d.ts +29 -0
- package/dist/types/options.d.ts +92 -0
- package/dist/types/setup.d.ts +1 -0
- package/dist/types/types.d.ts +241 -0
- package/jest-preset.js +18 -0
- package/package.json +120 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { assert, createModuleLogger } from '@metamask/utils';
|
|
2
|
+
import { waitFor as waitForPuppeteer } from 'pptr-testing-library';
|
|
3
|
+
import { rootLogger } from './logger';
|
|
4
|
+
const log = createModuleLogger(rootLogger, 'wait-for');
|
|
5
|
+
/**
|
|
6
|
+
* Wait for a condition to be true. This is a wrapper around
|
|
7
|
+
* `pptr-testing-library`'s `waitFor` function, with the addition of a custom
|
|
8
|
+
* error message.
|
|
9
|
+
*
|
|
10
|
+
* @param fn - The condition to wait for.
|
|
11
|
+
* @param options - The options.
|
|
12
|
+
* @param options.timeout - The timeout in milliseconds.
|
|
13
|
+
* @param options.message - The error message to throw if the condition is not
|
|
14
|
+
* met.
|
|
15
|
+
* @returns A promise that resolves when the condition is met. The promise
|
|
16
|
+
* resolves to the return value of the condition function.
|
|
17
|
+
*/ export async function waitFor(fn, { timeout = 3000, message } = {}) {
|
|
18
|
+
try {
|
|
19
|
+
let result;
|
|
20
|
+
await waitForPuppeteer(// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
21
|
+
async ()=>{
|
|
22
|
+
// Puppeteer's `waitFor` function does not support returning a value
|
|
23
|
+
// from the condition function, so we need to use a variable outside
|
|
24
|
+
// the scope of the function.
|
|
25
|
+
result = await fn();
|
|
26
|
+
}, {
|
|
27
|
+
timeout
|
|
28
|
+
});
|
|
29
|
+
assert(result !== undefined);
|
|
30
|
+
return result;
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (message) {
|
|
33
|
+
throw new Error(message);
|
|
34
|
+
}
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Wait for a JSON-RPC response.
|
|
40
|
+
*
|
|
41
|
+
* @param page - The page to wait for the response on.
|
|
42
|
+
* @param type - The type of response to wait for.
|
|
43
|
+
* @returns The JSON-RPC response.
|
|
44
|
+
*/ export async function waitForResponse(page, type) {
|
|
45
|
+
log('Waiting for response of type %s.', type);
|
|
46
|
+
return await page.evaluate(async (_type)=>{
|
|
47
|
+
return new Promise((resolve)=>{
|
|
48
|
+
window.__SIMULATOR_API__.dispatch({
|
|
49
|
+
type: `${_type}/clearResponse`
|
|
50
|
+
});
|
|
51
|
+
const unsubscribe = window.__SIMULATOR_API__.subscribe(()=>{
|
|
52
|
+
const state = window.__SIMULATOR_API__.getState();
|
|
53
|
+
const { pending, response } = state[_type];
|
|
54
|
+
if (!pending && response) {
|
|
55
|
+
unsubscribe();
|
|
56
|
+
resolve(response);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}, type);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=wait-for.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/wait-for.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assert, createModuleLogger } from '@metamask/utils';\nimport { waitFor as waitForPuppeteer } from 'pptr-testing-library';\nimport { Page } from 'puppeteer';\n\nimport { SnapResponse } from '../types';\nimport { rootLogger } from './logger';\n\nexport type WaitForOptions = {\n /**\n * The timeout in milliseconds.\n */\n timeout?: number;\n\n /**\n * The error message to throw if the condition is not met.\n */\n message?: string;\n};\n\nconst log = createModuleLogger(rootLogger, 'wait-for');\n\n/**\n * Wait for a condition to be true. This is a wrapper around\n * `pptr-testing-library`'s `waitFor` function, with the addition of a custom\n * error message.\n *\n * @param fn - The condition to wait for.\n * @param options - The options.\n * @param options.timeout - The timeout in milliseconds.\n * @param options.message - The error message to throw if the condition is not\n * met.\n * @returns A promise that resolves when the condition is met. The promise\n * resolves to the return value of the condition function.\n */\nexport async function waitFor<Result>(\n fn: () => Promise<Result>,\n { timeout = 3000, message }: WaitForOptions = {},\n) {\n try {\n let result: Result | undefined;\n\n await waitForPuppeteer(\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n // Puppeteer's `waitFor` function does not support returning a value\n // from the condition function, so we need to use a variable outside\n // the scope of the function.\n result = await fn();\n },\n {\n timeout,\n },\n );\n\n assert(result !== undefined);\n return result;\n } catch (error) {\n if (message) {\n throw new Error(message);\n }\n\n throw error;\n }\n}\n\n/**\n * Wait for a JSON-RPC response.\n *\n * @param page - The page to wait for the response on.\n * @param type - The type of response to wait for.\n * @returns The JSON-RPC response.\n */\nexport async function waitForResponse(\n page: Page,\n type:\n | HandlerType.OnTransaction\n | HandlerType.OnRpcRequest\n | HandlerType.OnCronjob,\n) {\n log('Waiting for response of type %s.', type);\n\n return await page.evaluate(async (_type) => {\n return new Promise<SnapResponse['response']>((resolve) => {\n window.__SIMULATOR_API__.dispatch({\n type: `${_type}/clearResponse`,\n });\n\n const unsubscribe = window.__SIMULATOR_API__.subscribe(() => {\n const state = window.__SIMULATOR_API__.getState();\n const { pending, response } = state[_type];\n\n if (!pending && response) {\n unsubscribe();\n\n resolve(response);\n }\n });\n });\n }, type);\n}\n"],"names":["assert","createModuleLogger","waitFor","waitForPuppeteer","rootLogger","log","fn","timeout","message","result","undefined","error","Error","waitForResponse","page","type","evaluate","_type","Promise","resolve","window","__SIMULATOR_API__","dispatch","unsubscribe","subscribe","state","getState","pending","response"],"mappings":"AACA,SAASA,MAAM,EAAEC,kBAAkB,QAAQ,kBAAkB;AAC7D,SAASC,WAAWC,gBAAgB,QAAQ,uBAAuB;AAInE,SAASC,UAAU,QAAQ,WAAW;AActC,MAAMC,MAAMJ,mBAAmBG,YAAY;AAE3C;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeF,QACpBI,EAAyB,EACzB,EAAEC,UAAU,IAAI,EAAEC,OAAO,EAAkB,GAAG,CAAC,CAAC;IAEhD,IAAI;QACF,IAAIC;QAEJ,MAAMN,iBACJ,kEAAkE;QAClE;YACE,oEAAoE;YACpE,oEAAoE;YACpE,6BAA6B;YAC7BM,SAAS,MAAMH;QACjB,GACA;YACEC;QACF;QAGFP,OAAOS,WAAWC;QAClB,OAAOD;IACT,EAAE,OAAOE,OAAO;QACd,IAAIH,SAAS;YACX,MAAM,IAAII,MAAMJ;QAClB;QAEA,MAAMG;IACR;AACF;AAEA;;;;;;CAMC,GACD,OAAO,eAAeE,gBACpBC,IAAU,EACVC,IAGyB;IAEzBV,IAAI,oCAAoCU;IAExC,OAAO,MAAMD,KAAKE,QAAQ,CAAC,OAAOC;QAChC,OAAO,IAAIC,QAAkC,CAACC;YAC5CC,OAAOC,iBAAiB,CAACC,QAAQ,CAAC;gBAChCP,MAAM,CAAC,EAAEE,MAAM,cAAc,CAAC;YAChC;YAEA,MAAMM,cAAcH,OAAOC,iBAAiB,CAACG,SAAS,CAAC;gBACrD,MAAMC,QAAQL,OAAOC,iBAAiB,CAACK,QAAQ;gBAC/C,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAE,GAAGH,KAAK,CAACR,MAAM;gBAE1C,IAAI,CAACU,WAAWC,UAAU;oBACxBL;oBAEAJ,QAAQS;gBACV;YACF;QACF;IACF,GAAGb;AACL"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/* eslint-disable no-invalid-this */ // Note: Because this file imports from `@jest/globals`, it can only be used in
|
|
2
|
+
// a Jest environment. This is why it's not exported from the index file.
|
|
3
|
+
import { expect } from '@jest/globals';
|
|
4
|
+
import { hasProperty } from '@metamask/utils';
|
|
5
|
+
import { diff, matcherErrorMessage, matcherHint, printReceived, printWithType, RECEIVED_COLOR } from 'jest-matcher-utils';
|
|
6
|
+
import { is } from 'superstruct';
|
|
7
|
+
import { InterfaceStruct, SnapResponseStruct } from './internals';
|
|
8
|
+
/**
|
|
9
|
+
* Ensure that the actual value is a response from the `request` function.
|
|
10
|
+
*
|
|
11
|
+
* @param actual - The actual value.
|
|
12
|
+
* @param matcherName - The name of the matcher.
|
|
13
|
+
* @param options - The matcher options.
|
|
14
|
+
*/ function assertActualIsSnapResponse(actual, matcherName, options) {
|
|
15
|
+
if (!is(actual, SnapResponseStruct)) {
|
|
16
|
+
throw new Error(matcherErrorMessage(matcherHint(matcherName, undefined, undefined, options), `${RECEIVED_COLOR('received')} value must be a response from the \`request\` function`, printWithType('Received', actual, printReceived)));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Ensure that the actual value is a response from the `request` function, and
|
|
21
|
+
* that it has a `ui` property.
|
|
22
|
+
*
|
|
23
|
+
* @param actual - The actual value.
|
|
24
|
+
* @param matcherName - The name of the matcher.
|
|
25
|
+
* @param options - The matcher options.
|
|
26
|
+
*/ function assertHasInterface(actual, matcherName, options) {
|
|
27
|
+
if (!is(actual, InterfaceStruct) || !actual.content) {
|
|
28
|
+
throw new Error(matcherErrorMessage(matcherHint(matcherName, undefined, undefined, options), `${RECEIVED_COLOR('received')} value must have a \`content\` property`, printWithType('Received', actual, printReceived)));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Check if a JSON-RPC response matches the expected value. This matcher is
|
|
33
|
+
* intended to be used with the `expect` global.
|
|
34
|
+
*
|
|
35
|
+
* @param actual - The actual response.
|
|
36
|
+
* @param expected - The expected response.
|
|
37
|
+
* @returns The status and message.
|
|
38
|
+
*/ export const toRespondWith = function(actual, expected) {
|
|
39
|
+
assertActualIsSnapResponse(actual, 'toRespondWith');
|
|
40
|
+
const { response } = actual;
|
|
41
|
+
if (hasProperty(response, 'error')) {
|
|
42
|
+
const message = ()=>`${this.utils.matcherHint('.toRespondWith')}\n\n` + `Expected response: ${this.utils.printExpected(expected)}\n` + `Received error: ${this.utils.printReceived(response.error)}`;
|
|
43
|
+
return {
|
|
44
|
+
message,
|
|
45
|
+
pass: false
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const pass = this.equals(response.result, expected);
|
|
49
|
+
const message = pass ? ()=>`${this.utils.matcherHint('.not.toRespondWith')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(response.result)}` : ()=>`${this.utils.matcherHint('.toRespondWith')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(response.result)}`;
|
|
50
|
+
return {
|
|
51
|
+
message,
|
|
52
|
+
pass
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
export const toRespondWithError = function(actual, expected) {
|
|
56
|
+
assertActualIsSnapResponse(actual, 'toRespondWithError');
|
|
57
|
+
const { response } = actual;
|
|
58
|
+
if (hasProperty(response, 'result')) {
|
|
59
|
+
const message = ()=>`${this.utils.matcherHint('.toRespondWithError')}\n\n` + `Expected error: ${this.utils.printExpected(expected)}\n` + `Received result: ${this.utils.printReceived(response.result)}`;
|
|
60
|
+
return {
|
|
61
|
+
message,
|
|
62
|
+
pass: false
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const pass = this.equals(response.error, expected);
|
|
66
|
+
const message = pass ? ()=>`${this.utils.matcherHint('.not.toRespondWithError')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(response.error)}` : ()=>`${this.utils.matcherHint('.toRespondWithError')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(response.error)}`;
|
|
67
|
+
return {
|
|
68
|
+
message,
|
|
69
|
+
pass
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Check if the snap sent a notification with the expected message. This matcher
|
|
74
|
+
* is intended to be used with the `expect` global.
|
|
75
|
+
*
|
|
76
|
+
* @param actual - The actual response.
|
|
77
|
+
* @param expected - The expected notification message.
|
|
78
|
+
* @param type - The expected notification type.
|
|
79
|
+
* @returns The status and message.
|
|
80
|
+
*/ export const toSendNotification = async function(actual, expected, type) {
|
|
81
|
+
assertActualIsSnapResponse(actual, 'toSendNotification');
|
|
82
|
+
const { notifications } = actual;
|
|
83
|
+
const pass = notifications.some((notification)=>this.equals(notification.message, expected) && (type === undefined || notification.type === type));
|
|
84
|
+
const message = pass ? ()=>`${this.utils.matcherHint('.not.toSendNotification')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Expected type: ${this.utils.printExpected(type)}\n` + `Received: ${this.utils.printReceived(notifications)}` : ()=>`${this.utils.matcherHint('.toSendNotification')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Expected type: ${this.utils.printExpected(type)}\n` + `Received: ${this.utils.printReceived(notifications)}`;
|
|
85
|
+
return {
|
|
86
|
+
message,
|
|
87
|
+
pass
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
export const toRender = function(actual, expected) {
|
|
91
|
+
assertHasInterface(actual, 'toRender');
|
|
92
|
+
const { content } = actual;
|
|
93
|
+
const pass = this.equals(content, expected);
|
|
94
|
+
const difference = diff(expected, content);
|
|
95
|
+
const message = pass ? ()=>`${this.utils.matcherHint('.not.toShowInterface')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(content)}` + `${difference ? `\n\nDifference:\n\n${difference}` : ''}` : ()=>`${this.utils.matcherHint('.toShowInterface')}\n\n` + `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(content)}` + `${difference ? `\n\nDifference:\n\n${difference}` : ''}`;
|
|
96
|
+
return {
|
|
97
|
+
message,
|
|
98
|
+
pass
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
expect.extend({
|
|
102
|
+
toRespondWith,
|
|
103
|
+
toRespondWithError,
|
|
104
|
+
toSendNotification,
|
|
105
|
+
toRender
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=matchers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/matchers.ts"],"sourcesContent":["/* eslint-disable no-invalid-this */\n\n// Note: Because this file imports from `@jest/globals`, it can only be used in\n// a Jest environment. This is why it's not exported from the index file.\n\nimport { expect } from '@jest/globals';\nimport { NotificationType } from '@metamask/rpc-methods';\nimport { Component } from '@metamask/snaps-ui';\nimport { EnumToUnion } from '@metamask/snaps-utils';\nimport { hasProperty, Json } from '@metamask/utils';\nimport type { MatcherFunction } from 'expect';\nimport {\n diff,\n matcherErrorMessage,\n matcherHint,\n MatcherHintOptions,\n printReceived,\n printWithType,\n RECEIVED_COLOR,\n} from 'jest-matcher-utils';\nimport { is } from 'superstruct';\n\nimport { InterfaceStruct, SnapResponseStruct } from './internals';\nimport { SnapResponse } from './types';\n\n/**\n * Ensure that the actual value is a response from the `request` function.\n *\n * @param actual - The actual value.\n * @param matcherName - The name of the matcher.\n * @param options - The matcher options.\n */\nfunction assertActualIsSnapResponse(\n actual: unknown,\n matcherName: string,\n options?: MatcherHintOptions,\n): asserts actual is SnapResponse {\n if (!is(actual, SnapResponseStruct)) {\n throw new Error(\n matcherErrorMessage(\n matcherHint(matcherName, undefined, undefined, options),\n `${RECEIVED_COLOR(\n 'received',\n )} value must be a response from the \\`request\\` function`,\n printWithType('Received', actual, printReceived),\n ),\n );\n }\n}\n\n/**\n * Ensure that the actual value is a response from the `request` function, and\n * that it has a `ui` property.\n *\n * @param actual - The actual value.\n * @param matcherName - The name of the matcher.\n * @param options - The matcher options.\n */\nfunction assertHasInterface(\n actual: unknown,\n matcherName: string,\n options?: MatcherHintOptions,\n): asserts actual is { content: Component } {\n if (!is(actual, InterfaceStruct) || !actual.content) {\n throw new Error(\n matcherErrorMessage(\n matcherHint(matcherName, undefined, undefined, options),\n `${RECEIVED_COLOR('received')} value must have a \\`content\\` property`,\n printWithType('Received', actual, printReceived),\n ),\n );\n }\n}\n\n/**\n * Check if a JSON-RPC response matches the expected value. This matcher is\n * intended to be used with the `expect` global.\n *\n * @param actual - The actual response.\n * @param expected - The expected response.\n * @returns The status and message.\n */\nexport const toRespondWith: MatcherFunction<[expected: Json]> = function (\n actual,\n expected,\n) {\n assertActualIsSnapResponse(actual, 'toRespondWith');\n\n const { response } = actual;\n if (hasProperty(response, 'error')) {\n const message = () =>\n `${this.utils.matcherHint('.toRespondWith')}\\n\\n` +\n `Expected response: ${this.utils.printExpected(expected)}\\n` +\n `Received error: ${this.utils.printReceived(response.error)}`;\n\n return { message, pass: false };\n }\n\n const pass = this.equals(response.result, expected);\n const message = pass\n ? () =>\n `${this.utils.matcherHint('.not.toRespondWith')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Received: ${this.utils.printReceived(response.result)}`\n : () =>\n `${this.utils.matcherHint('.toRespondWith')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Received: ${this.utils.printReceived(response.result)}`;\n\n return { message, pass };\n};\n\nexport const toRespondWithError: MatcherFunction<[expected: Json]> = function (\n actual,\n expected,\n) {\n assertActualIsSnapResponse(actual, 'toRespondWithError');\n\n const { response } = actual;\n if (hasProperty(response, 'result')) {\n const message = () =>\n `${this.utils.matcherHint('.toRespondWithError')}\\n\\n` +\n `Expected error: ${this.utils.printExpected(expected)}\\n` +\n `Received result: ${this.utils.printReceived(response.result)}`;\n\n return { message, pass: false };\n }\n\n const pass = this.equals(response.error, expected);\n const message = pass\n ? () =>\n `${this.utils.matcherHint('.not.toRespondWithError')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Received: ${this.utils.printReceived(response.error)}`\n : () =>\n `${this.utils.matcherHint('.toRespondWithError')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Received: ${this.utils.printReceived(response.error)}`;\n\n return { message, pass };\n};\n\n/**\n * Check if the snap sent a notification with the expected message. This matcher\n * is intended to be used with the `expect` global.\n *\n * @param actual - The actual response.\n * @param expected - The expected notification message.\n * @param type - The expected notification type.\n * @returns The status and message.\n */\nexport const toSendNotification: MatcherFunction<\n [expected: string, type?: EnumToUnion<NotificationType> | undefined]\n> = async function (actual, expected, type) {\n assertActualIsSnapResponse(actual, 'toSendNotification');\n\n const { notifications } = actual;\n const pass = notifications.some(\n (notification) =>\n this.equals(notification.message, expected) &&\n (type === undefined || notification.type === type),\n );\n\n const message = pass\n ? () =>\n `${this.utils.matcherHint('.not.toSendNotification')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Expected type: ${this.utils.printExpected(type)}\\n` +\n `Received: ${this.utils.printReceived(notifications)}`\n : () =>\n `${this.utils.matcherHint('.toSendNotification')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Expected type: ${this.utils.printExpected(type)}\\n` +\n `Received: ${this.utils.printReceived(notifications)}`;\n\n return { message, pass };\n};\n\nexport const toRender: MatcherFunction<[expected: Component]> = function (\n actual,\n expected,\n) {\n assertHasInterface(actual, 'toRender');\n\n const { content } = actual;\n const pass = this.equals(content, expected);\n\n const difference = diff(expected, content);\n\n const message = pass\n ? () =>\n `${this.utils.matcherHint('.not.toShowInterface')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Received: ${this.utils.printReceived(content)}` +\n `${difference ? `\\n\\nDifference:\\n\\n${difference}` : ''}`\n : () =>\n `${this.utils.matcherHint('.toShowInterface')}\\n\\n` +\n `Expected: ${this.utils.printExpected(expected)}\\n` +\n `Received: ${this.utils.printReceived(content)}` +\n `${difference ? `\\n\\nDifference:\\n\\n${difference}` : ''}`;\n\n return { message, pass };\n};\n\nexpect.extend({\n toRespondWith,\n toRespondWithError,\n toSendNotification,\n toRender,\n});\n"],"names":["expect","hasProperty","diff","matcherErrorMessage","matcherHint","printReceived","printWithType","RECEIVED_COLOR","is","InterfaceStruct","SnapResponseStruct","assertActualIsSnapResponse","actual","matcherName","options","Error","undefined","assertHasInterface","content","toRespondWith","expected","response","message","utils","printExpected","error","pass","equals","result","toRespondWithError","toSendNotification","type","notifications","some","notification","toRender","difference","extend"],"mappings":"AAAA,kCAAkC,GAElC,+EAA+E;AAC/E,yEAAyE;AAEzE,SAASA,MAAM,QAAQ,gBAAgB;AAIvC,SAASC,WAAW,QAAc,kBAAkB;AAEpD,SACEC,IAAI,EACJC,mBAAmB,EACnBC,WAAW,EAEXC,aAAa,EACbC,aAAa,EACbC,cAAc,QACT,qBAAqB;AAC5B,SAASC,EAAE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AAC,UAAU,EAAE,IAAI,CAACR,KAAK,CAAClB,aAAa,CAAC2B,eAAe,CAAC;IAE5D,OAAO;QAAEV;QAASI;IAAK;AACzB,EAAE;AAEF,OAAO,MAAMS,WAAmD,SAC9DvB,MAAM,EACNQ,QAAQ;IAERH,mBAAmBL,QAAQ;IAE3B,MAAM,EAAEM,OAAO,EAAE,GAAGN;IACpB,MAAMc,OAAO,IAAI,CAACC,MAAM,CAACT,SAASE;IAElC,MAAMgB,aAAalC,KAAKkB,UAAUF;IAElC,MAAMI,UAAUI,OACZ,IACE,CAAC,EAAE,IAAI,CAACH,KAAK,CAACnB,WAAW,CAAC,wBAAwB,IAAI,CAAC,GACvD,CAAC,UAAU,EAAE,IAAI,CAACmB,KAAK,CAACC,aAAa,CAACJ,UAAU,EAAE,CAAC,GACnD,CAAC,UAAU,EAAE,IAAI,CAACG,KAAK,CAAClB,aAAa,CAACa,SAAS,CAAC,GAChD,CAAC,EAAEkB,aAAa,CAAC,mBAAmB,EAAEA,WAAW,CAAC,GAAG,GAAG,CAAC,GAC3D,IACE,CAAC,EAAE,IAAI,CAACb,KAAK,CAACnB,WAAW,CAAC,oBAAoB,IAAI,CAAC,GACnD,CAAC,UAAU,EAAE,IAAI,CAACmB,KAAK,CAACC,aAAa,CAACJ,UAAU,EAAE,CAAC,GACnD,CAAC,UAAU,EAAE,IAAI,CAACG,KAAK,CAAClB,aAAa,CAACa,SAAS,CAAC,GAChD,CAAC,EAAEkB,aAAa,CAAC,mBAAmB,EAAEA,WAAW,CAAC,GAAG,GAAG,CAAC;IAE/D,OAAO;QAAEd;QAASI;IAAK;AACzB,EAAE;AAEF1B,OAAOqC,MAAM,CAAC;IACZlB;IACAU;IACAC;IACAK;AACF"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { boolean, create, defaulted, number, object, optional, string, type } from 'superstruct';
|
|
2
|
+
const SnapsEnvironmentOptionsStruct = type({
|
|
3
|
+
executionEnvironmentUrl: optional(string()),
|
|
4
|
+
simulatorUrl: optional(string()),
|
|
5
|
+
keepAlive: defaulted(boolean(), false),
|
|
6
|
+
server: defaulted(object({
|
|
7
|
+
enabled: defaulted(boolean(), true),
|
|
8
|
+
port: defaulted(number(), 0),
|
|
9
|
+
root: defaulted(string(), process.cwd())
|
|
10
|
+
}), {}),
|
|
11
|
+
browser: defaulted(object({
|
|
12
|
+
headless: defaulted(boolean(), true)
|
|
13
|
+
}), {})
|
|
14
|
+
});
|
|
15
|
+
/**
|
|
16
|
+
* Get the environment options. This validates the options, and returns the
|
|
17
|
+
* default options if none are provided.
|
|
18
|
+
*
|
|
19
|
+
* @param testEnvironmentOptions - The test environment options as defined in
|
|
20
|
+
* the Jest configuration.
|
|
21
|
+
* @returns The environment options.
|
|
22
|
+
*/ export function getOptions(testEnvironmentOptions) {
|
|
23
|
+
return create(testEnvironmentOptions, SnapsEnvironmentOptionsStruct);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=options.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/options.ts"],"sourcesContent":["import {\n boolean,\n create,\n defaulted,\n Infer,\n number,\n object,\n optional,\n string,\n type,\n} from 'superstruct';\n\nconst SnapsEnvironmentOptionsStruct = type({\n executionEnvironmentUrl: optional(string()),\n simulatorUrl: optional(string()),\n keepAlive: defaulted(boolean(), false),\n\n server: defaulted(\n object({\n enabled: defaulted(boolean(), true),\n port: defaulted(number(), 0),\n root: defaulted(string(), process.cwd()),\n }),\n {},\n ),\n\n browser: defaulted(\n object({\n headless: defaulted(boolean(), true),\n }),\n {},\n ),\n});\n\n/**\n * The options for the environment. These can be specified in the Jest\n * configuration under `testEnvironmentOptions`.\n *\n * @example\n * ```json\n * {\n * \"testEnvironment\": \"@metamask/snaps-jest\",\n * \"testEnvironmentOptions\": {\n * \"executionEnvironmentUrl\": \"http://localhost:8080\",\n * \"server\": {\n * \"port\": 8080,\n * /* ... *\\/\n * }\n * }\n * }\n * ```\n * @property executionEnvironmentUrl - The URL of the execution environment. If\n * this is not provided, the execution environment will be served from the\n * built-in HTTP server.\n * @property simulatorUrl - The URL of the simulator. If this is not provided,\n * the simulator will be served from the built-in HTTP server.\n * @property keepAlive - Whether to keep the browser open after the tests have\n * finished. This is useful for debugging. Defaults to `false`.\n * @property server - The options for the built-in HTTP server.\n * @property server.enabled - Whether to run the built-in HTTP server. Defaults\n * to `true`.\n * @property server.port - The port to use for the built-in HTTP server. If this\n * is not provided, a random available port will be used.\n * @property server.root - The root directory to serve from the built-in HTTP\n * server. Defaults to the current working directory. This is assumed to be the\n * directory containing the snap manifest and `dist` files. If this is a\n * relative path, it will be resolved relative to the current working directory.\n * @property browser - The options for the browser.\n * @property browser.headless - Whether to run the browser in headless mode.\n * Defaults to `true`.\n */\nexport type SnapsEnvironmentOptions = Infer<\n typeof SnapsEnvironmentOptionsStruct\n>;\n\n/**\n * Get the environment options. This validates the options, and returns the\n * default options if none are provided.\n *\n * @param testEnvironmentOptions - The test environment options as defined in\n * the Jest configuration.\n * @returns The environment options.\n */\nexport function getOptions(testEnvironmentOptions: Record<string, unknown>) {\n return create(testEnvironmentOptions, SnapsEnvironmentOptionsStruct);\n}\n"],"names":["boolean","create","defaulted","number","object","optional","string","type","SnapsEnvironmentOptionsStruct","executionEnvironmentUrl","simulatorUrl","keepAlive","server","enabled","port","root","process","cwd","browser","headless","getOptions","testEnvironmentOptions"],"mappings":"AAAA,SACEA,OAAO,EACPC,MAAM,EACNC,SAAS,EAETC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,IAAI,QACC,cAAc;AAErB,MAAMC,gCAAgCD,KAAK;IACzCE,yBAAyBJ,SAASC;IAClCI,cAAcL,SAASC;IACvBK,WAAWT,UAAUF,WAAW;IAEhCY,QAAQV,UACNE,OAAO;QACLS,SAASX,UAAUF,WAAW;QAC9Bc,MAAMZ,UAAUC,UAAU;QAC1BY,MAAMb,UAAUI,UAAUU,QAAQC,GAAG;IACvC,IACA,CAAC;IAGHC,SAAShB,UACPE,OAAO;QACLe,UAAUjB,UAAUF,WAAW;IACjC,IACA,CAAC;AAEL;AA2CA;;;;;;;CAOC,GACD,OAAO,SAASoB,WAAWC,sBAA+C;IACxE,OAAOpB,OAAOoB,wBAAwBb;AACxC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/setup.ts"],"sourcesContent":["// Setup file for Jest. This file is used in the Jest preset configuration, and\n// not intended to be exported or used directly.\n\n// eslint-disable-next-line import/no-unassigned-import\nimport './matchers';\n"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,gDAAgD;AAEhD,uDAAuD;AACvD,OAAO,aAAa"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import { NotificationType } from '@metamask/rpc-methods';\nimport { Component } from '@metamask/snaps-ui';\nimport { EnumToUnion } from '@metamask/snaps-utils';\nimport { JsonRpcId, JsonRpcParams } from '@metamask/utils';\nimport { Infer } from 'superstruct';\n\nimport {\n Mock,\n MockJsonRpcOptions,\n MockOptions,\n SnapOptionsStruct,\n SnapResponseStruct,\n TransactionOptionsStruct,\n} from './internals';\n\n/* eslint-disable @typescript-eslint/consistent-type-definitions */\ndeclare module 'expect' {\n interface AsymmetricMatchers {\n toRespondWith(response: unknown): void;\n toRespondWithError(error: unknown): void;\n toSendNotification(\n message: string,\n type?: EnumToUnion<NotificationType>,\n ): void;\n toRender(component: Component): void;\n }\n\n // Ideally we would use `Matchers<Result>` instead of `Matchers<R>`, but\n // TypeScript doesn't allow this:\n // TS2428: All declarations of 'Matchers' must have identical type parameters.\n interface Matchers<R> {\n toRespondWith(response: unknown): R;\n toRespondWithError(error: unknown): R;\n toSendNotification(\n message: string,\n type?: EnumToUnion<NotificationType>,\n ): R;\n toRender(component: Component): R;\n }\n}\n/* eslint-enable @typescript-eslint/consistent-type-definitions */\n\n/**\n * Deeply partialize a type.\n *\n * @template Type - The type to partialize.\n * @returns The deeply partialized type.\n * @example\n * ```ts\n * type Foo = {\n * bar: {\n * baz: string;\n * };\n * qux: number;\n * };\n *\n * type PartialFoo = DeepPartial<Foo>;\n * // { bar?: { baz?: string; }; qux?: number; }\n * ```\n */\nexport type DeepPartial<Type> = {\n [Key in keyof Type]?: Type[Key] extends Record<string, unknown>\n ? DeepPartial<Type[Key]>\n : Type[Key];\n};\n\nexport type RequestOptions = {\n /**\n * The JSON-RPC request ID.\n */\n id?: JsonRpcId;\n\n /**\n * The JSON-RPC method.\n */\n method: string;\n\n /**\n * The JSON-RPC params.\n */\n params?: JsonRpcParams;\n\n /**\n * The origin to send the request from.\n */\n origin?: string;\n};\n\n/**\n * The `runCronjob` options. This is the same as {@link RequestOptions}, except\n * that it does not have an `origin` property.\n */\nexport type CronjobOptions = Omit<RequestOptions, 'origin'>;\n\n/**\n * The options to use for transaction requests.\n *\n * @property chainId - The CAIP-2 chain ID to send the transaction on. Defaults\n * to `eip155:1`.\n * @property origin - The origin to send the transaction from. Defaults to\n * `metamask.io`.\n * @property from - The address to send the transaction from. Defaults to a\n * randomly generated address.\n * @property to - The address to send the transaction to. Defaults to a randomly\n * generated address.\n * @property value - The value to send with the transaction. Defaults to `0`.\n * @property data - The data to send with the transaction. Defaults to `0x`.\n * @property gasLimit - The gas limit to use for the transaction. Defaults to\n * `21_000`.\n * @property maxFeePerGas - The maximum fee per gas to use for the transaction.\n * Defaults to `1`.\n * @property maxPriorityFeePerGas - The maximum priority fee per gas to use for\n * the transaction. Defaults to `1`.\n * @property nonce - The nonce to use for the transaction. Defaults to `0`.\n */\nexport type TransactionOptions = Infer<typeof TransactionOptionsStruct>;\n\n/**\n * The options to use for requests to the snap.\n *\n * @property timeout - The timeout in milliseconds to use. Defaults to `1000`.\n */\nexport type SnapOptions = Infer<typeof SnapOptionsStruct>;\n\n/**\n * A `snap_dialog` alert interface.\n */\nexport type SnapAlertInterface = {\n /**\n * The type of the interface. This is always `alert`.\n */\n type: 'alert';\n\n /**\n * The content to show in the alert.\n */\n content: Component;\n\n /**\n * Close the alert.\n */\n ok(): Promise<void>;\n};\n\n/**\n * A `snap_dialog` confirmation interface.\n */\nexport type SnapConfirmationInterface = {\n /**\n * The type of the interface. This is always `confirmation`.\n */\n type: 'confirmation';\n\n /**\n * The content to show in the confirmation.\n */\n content: Component;\n\n /**\n * Close the confirmation.\n */\n ok(): Promise<void>;\n\n /**\n * Cancel the confirmation.\n */\n cancel(): Promise<void>;\n};\n\n/**\n * A `snap_dialog` prompt interface.\n */\nexport type SnapPromptInterface = {\n /**\n * The type of the interface. This is always `prompt`.\n */\n type: 'prompt';\n\n /**\n * The content to show in the prompt.\n */\n content: Component;\n\n /**\n * Close the prompt.\n *\n * @param value - The value to close the prompt with.\n */\n ok(value?: string): Promise<void>;\n\n /**\n * Cancel the prompt.\n */\n cancel(): Promise<void>;\n};\n\nexport type SnapInterface =\n | SnapAlertInterface\n | SnapConfirmationInterface\n | SnapPromptInterface;\n\nexport type SnapRequestObject = {\n /**\n * Get a user interface object from a snap. This will throw an error if the\n * snap does not show a user interface within the timeout.\n *\n * @param options - The options to use.\n * @param options.timeout - The timeout in milliseconds to use. Defaults to\n * `1000`.\n * @returns The user interface object.\n */\n getInterface(options?: SnapOptions): Promise<SnapInterface>;\n};\n\n/**\n * A pending request object. This is a promise with extra\n * {@link SnapRequestObject} fields.\n */\nexport type SnapRequest = Promise<SnapResponse> & SnapRequestObject;\n\n/**\n * This is the main entry point to interact with the snap. It is returned by\n * {@link installSnap}, and has methods to send requests to the snap.\n *\n * @example\n * ```ts\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * const snap = await installSnap();\n * const response = await snap.request({ method: 'hello' });\n *\n * expect(response).toRespondWith('Hello, world!');\n * ```\n */\nexport type Snap = {\n /**\n * Send a JSON-RPC request to the snap.\n *\n * @param request - The request. This is similar to a JSON-RPC request, but\n * has an extra `origin` field.\n * @returns The response promise, with extra {@link SnapRequestObject} fields.\n */\n request(request: RequestOptions): SnapRequest;\n\n /**\n * Send a transaction to the snap.\n *\n * @param transaction - The transaction. This is similar to an Ethereum\n * transaction object, but has an extra `origin` field. Any missing fields\n * will be filled in with default values.\n * @returns The response.\n */\n sendTransaction(\n transaction?: Partial<TransactionOptions>,\n ): Promise<SnapResponse>;\n\n /**\n * Run a cronjob in the snap. This is similar to {@link request}, but the\n * request will be sent to the `onCronjob` method of the snap.\n *\n * @param cronjob - The cronjob request. This is similar to a JSON-RPC\n * request, and is normally specified in the snap manifest, under the\n * `endowment:cronjob` permission.\n * @returns The response promise, with extra {@link SnapRequestObject} fields.\n */\n runCronjob(cronjob: CronjobOptions): SnapRequest;\n\n /**\n * Close the page running the snap. This is mainly useful for cleaning up\n * the test environment, and calling it is not strictly necessary.\n *\n * @returns A promise that resolves when the page is closed.\n */\n // TODO: Find a way to do this automatically.\n close(): Promise<void>;\n\n /**\n * Enable network mocking for the snap.\n *\n * @param options - The options for the network mocking.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\n mock(options: DeepPartial<MockOptions>): Promise<Mock>;\n\n /**\n * Enable JSON-RPC provider mocking for the snap. This will mock any requests\n * sent through the `ethereum` global, with the specified `method`.\n *\n * @param options - The options for the JSON-RPC mocking.\n * @param options.method - The JSON-RPC method to mock, e.g.,\n * `eth_blockNumber`.\n * @param options.result - The JSON value to return.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\n mockJsonRpc(options: MockJsonRpcOptions): Promise<Mock>;\n};\n\nexport type SnapResponse = Infer<typeof SnapResponseStruct>;\n\nexport { NotificationType } from '@metamask/rpc-methods';\n"],"names":["NotificationType"],"mappings":"AA2SA,SAASA,gBAAgB,QAAQ,wBAAwB"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { EnvironmentContext, JestEnvironmentConfig } from '@jest/environment';
|
|
2
|
+
import NodeEnvironment from 'jest-environment-node';
|
|
3
|
+
declare global {
|
|
4
|
+
const browser: WebdriverIO.Browser;
|
|
5
|
+
const snapsEnvironment: SnapsEnvironment;
|
|
6
|
+
}
|
|
7
|
+
export declare class SnapsEnvironment extends NodeEnvironment {
|
|
8
|
+
#private;
|
|
9
|
+
browser: WebdriverIO.Browser;
|
|
10
|
+
/**
|
|
11
|
+
* Constructor.
|
|
12
|
+
*
|
|
13
|
+
* @param options - The environment options.
|
|
14
|
+
* @param context - The environment context.
|
|
15
|
+
*/
|
|
16
|
+
constructor(options: JestEnvironmentConfig, context: EnvironmentContext);
|
|
17
|
+
/**
|
|
18
|
+
* Set up the environment. This starts the built-in HTTP server, and creates a
|
|
19
|
+
* new browser instance.
|
|
20
|
+
*/
|
|
21
|
+
setup(): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Tear down the environment. This closes the browser, and stops the built-in
|
|
24
|
+
* HTTP server.
|
|
25
|
+
*/
|
|
26
|
+
teardown(): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Get the URL to the simulator, including the environment URL.
|
|
29
|
+
*
|
|
30
|
+
* @returns The simulator URL.
|
|
31
|
+
* @throws If the server is not running.
|
|
32
|
+
*/
|
|
33
|
+
get url(): string;
|
|
34
|
+
/**
|
|
35
|
+
* Get the snap ID for the current environment, which is used if no snap ID is
|
|
36
|
+
* passed to {@link installSnap}. This assumes that the built-in server is
|
|
37
|
+
* running.
|
|
38
|
+
*
|
|
39
|
+
* @returns The snap ID.
|
|
40
|
+
* @throws If the server is not running.
|
|
41
|
+
*/
|
|
42
|
+
get snapId(): string;
|
|
43
|
+
/**
|
|
44
|
+
* Create a new page, and attach logging handlers.
|
|
45
|
+
*
|
|
46
|
+
* @param url - The page URL. Defaults to the specified Snaps Simulator URL,
|
|
47
|
+
* or the default simulator URL if none is specified.
|
|
48
|
+
* @param timeout - The page timeout, in milliseconds.
|
|
49
|
+
* @returns The new page.
|
|
50
|
+
*/
|
|
51
|
+
createPage(url?: string, timeout?: number): Promise<import("puppeteer").Page>;
|
|
52
|
+
}
|
|
53
|
+
export default SnapsEnvironment;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Snap } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Load a snap into the environment. This is the main entry point for testing
|
|
4
|
+
* snaps: It returns a {@link Snap} object that can be used to interact with the
|
|
5
|
+
* snap.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { installSnap } from '@metamask/snaps-jest';
|
|
10
|
+
*
|
|
11
|
+
* describe('My Snap', () => {
|
|
12
|
+
* it('should do something', async () => {
|
|
13
|
+
* const { request } = await installSnap('local:my-snap');
|
|
14
|
+
* const response = await request({
|
|
15
|
+
* method: 'foo',
|
|
16
|
+
* params: ['bar'],
|
|
17
|
+
* });
|
|
18
|
+
* expect(response).toRespondWith('bar');
|
|
19
|
+
* });
|
|
20
|
+
* });
|
|
21
|
+
* ```
|
|
22
|
+
* @param snapId - The ID of the snap, including the prefix (`local:`). Defaults
|
|
23
|
+
* to the URL of the built-in server, if it is running. This supports both
|
|
24
|
+
* local snap IDs and NPM snap IDs.
|
|
25
|
+
* @returns The snap.
|
|
26
|
+
* @throws If the built-in server is not running, and no snap ID is provided.
|
|
27
|
+
*/
|
|
28
|
+
export declare function installSnap(snapId?: string): Promise<Snap>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Page } from 'puppeteer';
|
|
2
|
+
import { SnapInterface, SnapOptions } from '../types';
|
|
3
|
+
/**
|
|
4
|
+
* Get the current snap user interface (i.e., dialog). This will throw an error
|
|
5
|
+
* if the snap does not show a user interface within the timeout.
|
|
6
|
+
*
|
|
7
|
+
* @param page - The page to get the interface from.
|
|
8
|
+
* @param options - The options to use.
|
|
9
|
+
* @param options.timeout - The timeout in milliseconds to use. Defaults to
|
|
10
|
+
* `1000`.
|
|
11
|
+
* @returns The user interface object.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getInterface(page: Page, options?: SnapOptions): Promise<SnapInterface>;
|
|
14
|
+
/**
|
|
15
|
+
* Get the text of the notifications.
|
|
16
|
+
*
|
|
17
|
+
* @param page - The page to get the notifications from.
|
|
18
|
+
* @param requestId - The ID of the request to get the notifications for.
|
|
19
|
+
* @returns The text of the notifications, in order of appearance.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getNotifications(page: Page, requestId: string): Promise<{
|
|
22
|
+
id: string;
|
|
23
|
+
message: string;
|
|
24
|
+
type: "native" | "inApp";
|
|
25
|
+
}[]>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { Page, HTTPRequest } from 'puppeteer';
|
|
2
|
+
import { Infer, Struct } from 'superstruct';
|
|
3
|
+
import { DeepPartial } from '../types';
|
|
4
|
+
export declare type Unmock = () => Promise<void>;
|
|
5
|
+
export declare type Mock = {
|
|
6
|
+
/**
|
|
7
|
+
* A function that can be used to unmock the URL.
|
|
8
|
+
*/
|
|
9
|
+
unmock: Unmock;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* A function that can return `true` if the given request should be mocked, or
|
|
13
|
+
* false if not.
|
|
14
|
+
*
|
|
15
|
+
* @param request - The request to check.
|
|
16
|
+
* @returns Whether to mock the request.
|
|
17
|
+
*/
|
|
18
|
+
export declare type ConditionFunction = (request: HTTPRequest) => boolean;
|
|
19
|
+
export declare const MockOptionsStruct: Struct<{
|
|
20
|
+
response: {
|
|
21
|
+
headers: Record<string, unknown>;
|
|
22
|
+
status: number;
|
|
23
|
+
body: string;
|
|
24
|
+
contentType: string;
|
|
25
|
+
};
|
|
26
|
+
url: string | RegExp;
|
|
27
|
+
partial?: boolean | undefined;
|
|
28
|
+
} | {
|
|
29
|
+
response: {
|
|
30
|
+
headers: Record<string, unknown>;
|
|
31
|
+
status: number;
|
|
32
|
+
body: string;
|
|
33
|
+
contentType: string;
|
|
34
|
+
};
|
|
35
|
+
condition: ConditionFunction;
|
|
36
|
+
}, null>;
|
|
37
|
+
/**
|
|
38
|
+
* The options for the network mocking.
|
|
39
|
+
*
|
|
40
|
+
* @property url - The URL to mock. If a string is provided, the URL will be
|
|
41
|
+
* matched exactly. If a RegExp is provided, the URL will be matched against it.
|
|
42
|
+
* This option is incompatible with the `condition` option.
|
|
43
|
+
* @property partial - If enabled, the request will be mocked if the URL starts
|
|
44
|
+
* with the given URL. This option is ignored if a RegExp is provided to the
|
|
45
|
+
* `url` option. This option is incompatible with the `condition` option.
|
|
46
|
+
* @property condition - A function which gets the {@link HTTPRequest} as
|
|
47
|
+
* parameter and returns a boolean to indicate whether the response should be
|
|
48
|
+
* mocked or not. This option is incompatible with the `url` and `partial`
|
|
49
|
+
* options.
|
|
50
|
+
* @property response - The response to send for the request.
|
|
51
|
+
* @property response.status - The status code to send for the response.
|
|
52
|
+
* Defaults to `200`.
|
|
53
|
+
* @property response.headers - The headers to send for the response. Defaults
|
|
54
|
+
* to headers that enable CORS.
|
|
55
|
+
* @property response.contentType - The content type to send for the response.
|
|
56
|
+
* Defaults to `text/plain`.
|
|
57
|
+
*/
|
|
58
|
+
export declare type MockOptions = Infer<typeof MockOptionsStruct>;
|
|
59
|
+
/**
|
|
60
|
+
* Enable network mocking for the given page, and all its sub-frames.
|
|
61
|
+
*
|
|
62
|
+
* @param page - The page to enable network mocking on.
|
|
63
|
+
* @param options - The options for the network mocking.
|
|
64
|
+
* @returns A {@link Mock} object, with an `unmock` function.
|
|
65
|
+
*/
|
|
66
|
+
export declare function mock(page: Page, options: DeepPartial<MockOptions>): Promise<Mock>;
|
|
67
|
+
declare const MockJsonRpcOptionsStruct: Struct<{
|
|
68
|
+
method: string;
|
|
69
|
+
result: import("@metamask/utils").Json;
|
|
70
|
+
}, {
|
|
71
|
+
method: Struct<string, null>;
|
|
72
|
+
result: Struct<import("@metamask/utils").Json, unknown>;
|
|
73
|
+
}>;
|
|
74
|
+
export declare type MockJsonRpcOptions = Infer<typeof MockJsonRpcOptionsStruct>;
|
|
75
|
+
/**
|
|
76
|
+
* Mock an Ethereum JSON-RPC request. This intercepts all requests to the
|
|
77
|
+
* Ethereum provider, and returns the `result` instead.
|
|
78
|
+
*
|
|
79
|
+
* @param page - The page to enable network JSON-RPC mocking on.
|
|
80
|
+
* @param options - The options for the JSON-RPC mock.
|
|
81
|
+
* @param options.method - The JSON-RPC method to mock. Any other methods will be
|
|
82
|
+
* forwarded to the provider.
|
|
83
|
+
* @param options.result - The JSON response to return.
|
|
84
|
+
* @returns A {@link Mock} object, with an `unmock` function.
|
|
85
|
+
*/
|
|
86
|
+
export declare function mockJsonRpc(page: Page, { method, result }: MockJsonRpcOptions): Promise<Mock>;
|
|
87
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { HandlerType } from '@metamask/snaps-utils';
|
|
2
|
+
import { Page } from 'puppeteer';
|
|
3
|
+
import { CronjobOptions, RequestOptions, SnapRequest, TransactionOptions } from '../types';
|
|
4
|
+
/**
|
|
5
|
+
* Send a request to the snap.
|
|
6
|
+
*
|
|
7
|
+
* @param page - The page to send the request from.
|
|
8
|
+
* @param options - The request options.
|
|
9
|
+
* @param options.origin - The origin of the request. Defaults to `metamask.io`.
|
|
10
|
+
* @param handler - The handler to use. Defaults to `onRpcRequest`.
|
|
11
|
+
* @returns The response.
|
|
12
|
+
*/
|
|
13
|
+
export declare function request(page: Page, { origin, ...options }: RequestOptions, handler?: HandlerType.OnRpcRequest | HandlerType.OnCronjob): SnapRequest;
|
|
14
|
+
/**
|
|
15
|
+
* Send a transaction to the snap.
|
|
16
|
+
*
|
|
17
|
+
* @param page - The page to send the transaction from.
|
|
18
|
+
* @param options - The transaction options.
|
|
19
|
+
* @returns The response.
|
|
20
|
+
*/
|
|
21
|
+
export declare function sendTransaction(page: Page, options: Partial<TransactionOptions>): Promise<{
|
|
22
|
+
id: string;
|
|
23
|
+
response: ({
|
|
24
|
+
result: import("@metamask/utils").Json;
|
|
25
|
+
} | {
|
|
26
|
+
error: import("@metamask/utils").Json;
|
|
27
|
+
}) & Record<"error", unknown>;
|
|
28
|
+
notifications: never[];
|
|
29
|
+
content?: undefined;
|
|
30
|
+
} | {
|
|
31
|
+
id: string;
|
|
32
|
+
response: {
|
|
33
|
+
result: import("@metamask/utils").Json;
|
|
34
|
+
};
|
|
35
|
+
notifications: never[];
|
|
36
|
+
content: import("@metamask/snaps-ui").Panel | {
|
|
37
|
+
value: string;
|
|
38
|
+
type: import("@metamask/snaps-ui").NodeType.Copyable;
|
|
39
|
+
} | {
|
|
40
|
+
type: import("@metamask/snaps-ui").NodeType.Divider;
|
|
41
|
+
} | {
|
|
42
|
+
value: string;
|
|
43
|
+
type: import("@metamask/snaps-ui").NodeType.Heading;
|
|
44
|
+
} | {
|
|
45
|
+
type: import("@metamask/snaps-ui").NodeType.Spinner;
|
|
46
|
+
} | {
|
|
47
|
+
value: string;
|
|
48
|
+
type: import("@metamask/snaps-ui").NodeType.Text;
|
|
49
|
+
};
|
|
50
|
+
}>;
|
|
51
|
+
/**
|
|
52
|
+
* Run a cronjob.
|
|
53
|
+
*
|
|
54
|
+
* @param page - The page to run the cronjob from.
|
|
55
|
+
* @param options - The request options.
|
|
56
|
+
* @returns The response.
|
|
57
|
+
*/
|
|
58
|
+
export declare function runCronjob(page: Page, options: CronjobOptions): SnapRequest;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { Server } from 'http';
|
|
3
|
+
import { SnapsEnvironmentOptions } from '../options';
|
|
4
|
+
export declare type ServerOptions = Required<Required<SnapsEnvironmentOptions>['server']>;
|
|
5
|
+
/**
|
|
6
|
+
* Start an HTTP server on `localhost` with a random port. This is used to serve
|
|
7
|
+
* the static files for the environment.
|
|
8
|
+
*
|
|
9
|
+
* @param options - The options to use.
|
|
10
|
+
* @param options.port - The port to use for the server.
|
|
11
|
+
* @param options.root - The root directory to serve from the server.
|
|
12
|
+
* @returns The HTTP server.
|
|
13
|
+
*/
|
|
14
|
+
export declare function startServer(options: ServerOptions): Promise<Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>>;
|