@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,117 @@
|
|
|
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
|
+
"use strict";
|
|
4
|
+
Object.defineProperty(exports, "__esModule", {
|
|
5
|
+
value: true
|
|
6
|
+
});
|
|
7
|
+
function _export(target, all) {
|
|
8
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
9
|
+
enumerable: true,
|
|
10
|
+
get: all[name]
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
_export(exports, {
|
|
14
|
+
toRespondWith: function() {
|
|
15
|
+
return toRespondWith;
|
|
16
|
+
},
|
|
17
|
+
toRespondWithError: function() {
|
|
18
|
+
return toRespondWithError;
|
|
19
|
+
},
|
|
20
|
+
toSendNotification: function() {
|
|
21
|
+
return toSendNotification;
|
|
22
|
+
},
|
|
23
|
+
toRender: function() {
|
|
24
|
+
return toRender;
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
const _globals = require("@jest/globals");
|
|
28
|
+
const _utils = require("@metamask/utils");
|
|
29
|
+
const _jestmatcherutils = require("jest-matcher-utils");
|
|
30
|
+
const _superstruct = require("superstruct");
|
|
31
|
+
const _internals = require("./internals");
|
|
32
|
+
/**
|
|
33
|
+
* Ensure that the actual value is a response from the `request` function.
|
|
34
|
+
*
|
|
35
|
+
* @param actual - The actual value.
|
|
36
|
+
* @param matcherName - The name of the matcher.
|
|
37
|
+
* @param options - The matcher options.
|
|
38
|
+
*/ function assertActualIsSnapResponse(actual, matcherName, options) {
|
|
39
|
+
if (!(0, _superstruct.is)(actual, _internals.SnapResponseStruct)) {
|
|
40
|
+
throw new Error((0, _jestmatcherutils.matcherErrorMessage)((0, _jestmatcherutils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestmatcherutils.RECEIVED_COLOR)('received')} value must be a response from the \`request\` function`, (0, _jestmatcherutils.printWithType)('Received', actual, _jestmatcherutils.printReceived)));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Ensure that the actual value is a response from the `request` function, and
|
|
45
|
+
* that it has a `ui` property.
|
|
46
|
+
*
|
|
47
|
+
* @param actual - The actual value.
|
|
48
|
+
* @param matcherName - The name of the matcher.
|
|
49
|
+
* @param options - The matcher options.
|
|
50
|
+
*/ function assertHasInterface(actual, matcherName, options) {
|
|
51
|
+
if (!(0, _superstruct.is)(actual, _internals.InterfaceStruct) || !actual.content) {
|
|
52
|
+
throw new Error((0, _jestmatcherutils.matcherErrorMessage)((0, _jestmatcherutils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestmatcherutils.RECEIVED_COLOR)('received')} value must have a \`content\` property`, (0, _jestmatcherutils.printWithType)('Received', actual, _jestmatcherutils.printReceived)));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const toRespondWith = function(actual, expected) {
|
|
56
|
+
assertActualIsSnapResponse(actual, 'toRespondWith');
|
|
57
|
+
const { response } = actual;
|
|
58
|
+
if ((0, _utils.hasProperty)(response, 'error')) {
|
|
59
|
+
const message = ()=>`${this.utils.matcherHint('.toRespondWith')}\n\n` + `Expected response: ${this.utils.printExpected(expected)}\n` + `Received error: ${this.utils.printReceived(response.error)}`;
|
|
60
|
+
return {
|
|
61
|
+
message,
|
|
62
|
+
pass: false
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const pass = this.equals(response.result, expected);
|
|
66
|
+
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)}`;
|
|
67
|
+
return {
|
|
68
|
+
message,
|
|
69
|
+
pass
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
const toRespondWithError = function(actual, expected) {
|
|
73
|
+
assertActualIsSnapResponse(actual, 'toRespondWithError');
|
|
74
|
+
const { response } = actual;
|
|
75
|
+
if ((0, _utils.hasProperty)(response, 'result')) {
|
|
76
|
+
const message = ()=>`${this.utils.matcherHint('.toRespondWithError')}\n\n` + `Expected error: ${this.utils.printExpected(expected)}\n` + `Received result: ${this.utils.printReceived(response.result)}`;
|
|
77
|
+
return {
|
|
78
|
+
message,
|
|
79
|
+
pass: false
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
const pass = this.equals(response.error, expected);
|
|
83
|
+
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)}`;
|
|
84
|
+
return {
|
|
85
|
+
message,
|
|
86
|
+
pass
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
const toSendNotification = async function(actual, expected, type) {
|
|
90
|
+
assertActualIsSnapResponse(actual, 'toSendNotification');
|
|
91
|
+
const { notifications } = actual;
|
|
92
|
+
const pass = notifications.some((notification)=>this.equals(notification.message, expected) && (type === undefined || notification.type === type));
|
|
93
|
+
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)}`;
|
|
94
|
+
return {
|
|
95
|
+
message,
|
|
96
|
+
pass
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
const toRender = function(actual, expected) {
|
|
100
|
+
assertHasInterface(actual, 'toRender');
|
|
101
|
+
const { content } = actual;
|
|
102
|
+
const pass = this.equals(content, expected);
|
|
103
|
+
const difference = (0, _jestmatcherutils.diff)(expected, content);
|
|
104
|
+
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}` : ''}`;
|
|
105
|
+
return {
|
|
106
|
+
message,
|
|
107
|
+
pass
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
_globals.expect.extend({
|
|
111
|
+
toRespondWith,
|
|
112
|
+
toRespondWithError,
|
|
113
|
+
toSendNotification,
|
|
114
|
+
toRender
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
//# 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":["toRespondWith","toRespondWithError","toSendNotification","toRender","assertActualIsSnapResponse","actual","matcherName","options","is","SnapResponseStruct","Error","matcherErrorMessage","matcherHint","undefined","RECEIVED_COLOR","printWithType","printReceived","assertHasInterface","InterfaceStruct","content","expected","response","hasProperty","message","utils","printExpected","error","pass","equals","result","type","notifications","some","notification","difference","diff","expect","extend"],"mappings":"AAAA,kCAAkC,GAElC,+EAA+E;AAC/E,yEAAyE;;;;;;;;;;;;IA+E5DA,aAAa;eAAbA;;IA8BAC,kBAAkB;eAAlBA;;IAuCAC,kBAAkB;eAAlBA;;IA2BAC,QAAQ;eAARA;;;yBA7KU;uBAIW;kCAU3B;6BACY;2BAEiC;AAGpD;;;;;;CAMC,GACD,SAASC,2BACPC,MAAe,EACfC,WAAmB,EACnBC,OAA4B;IAE5B,IAAI,CAACC,IAAAA,eAAE,EAACH,QAAQI,6BAAkB,GAAG;QACnC,MAAM,IAAIC,MACRC,IAAAA,qCAAmB,EACjBC,IAAAA,6BAAW,EAACN,aAAaO,WAAWA,WAAWN,UAC/C,CAAC,EAAEO,IAAAA,gCAAc,EACf,YACA,uDAAuD,CAAC,EAC1DC,IAAAA,+BAAa,EAAC,YAAYV,QAAQW,+BAAa;IAGrD;AACF;AAEA;;;;;;;CAOC,GACD,SAASC,mBACPZ,MAAe,E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,EAAE,IAAI,CAACH,KAAK,CAACZ,WAAW,CAAC,wBAAwB,IAAI,CAAC,GACvD,CAAC,UAAU,EAAE,IAAI,CAACY,KAAK,CAACC,aAAa,CAACL,UAAU,EAAE,CAAC,GACnD,CAAC,UAAU,EAAE,IAAI,CAACI,KAAK,CAACR,aAAa,CAACG,SAAS,CAAC,GAChD,CAAC,EAAEe,aAAa,CAAC,mBAAmB,EAAEA,WAAW,CAAC,GAAG,GAAG,CAAC,GAC3D,IACE,CAAC,EAAE,IAAI,CAACV,KAAK,CAACZ,WAAW,CAAC,oBAAoB,IAAI,CAAC,GACnD,CAAC,UAAU,EAAE,IAAI,CAACY,KAAK,CAACC,aAAa,CAACL,UAAU,EAAE,CAAC,GACnD,CAAC,UAAU,EAAE,IAAI,CAACI,KAAK,CAACR,aAAa,CAACG,SAAS,CAAC,GAChD,CAAC,EAAEe,aAAa,CAAC,mBAAmB,EAAEA,WAAW,CAAC,GAAG,GAAG,CAAC;IAE/D,OAAO;QAAEX;QAASI;IAAK;AACzB;AAEAS,eAAM,CAACC,MAAM,CAAC;IACZrC;IACAC;IACAC;IACAC;AACF"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "getOptions", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return getOptions;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _superstruct = require("superstruct");
|
|
12
|
+
const SnapsEnvironmentOptionsStruct = (0, _superstruct.type)({
|
|
13
|
+
executionEnvironmentUrl: (0, _superstruct.optional)((0, _superstruct.string)()),
|
|
14
|
+
simulatorUrl: (0, _superstruct.optional)((0, _superstruct.string)()),
|
|
15
|
+
keepAlive: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), false),
|
|
16
|
+
server: (0, _superstruct.defaulted)((0, _superstruct.object)({
|
|
17
|
+
enabled: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), true),
|
|
18
|
+
port: (0, _superstruct.defaulted)((0, _superstruct.number)(), 0),
|
|
19
|
+
root: (0, _superstruct.defaulted)((0, _superstruct.string)(), process.cwd())
|
|
20
|
+
}), {}),
|
|
21
|
+
browser: (0, _superstruct.defaulted)((0, _superstruct.object)({
|
|
22
|
+
headless: (0, _superstruct.defaulted)((0, _superstruct.boolean)(), true)
|
|
23
|
+
}), {})
|
|
24
|
+
});
|
|
25
|
+
function getOptions(testEnvironmentOptions) {
|
|
26
|
+
return (0, _superstruct.create)(testEnvironmentOptions, SnapsEnvironmentOptionsStruct);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//# 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":["getOptions","SnapsEnvironmentOptionsStruct","type","executionEnvironmentUrl","optional","string","simulatorUrl","keepAlive","defaulted","boolean","server","object","enabled","port","number","root","process","cwd","browser","headless","testEnvironmentOptions","create"],"mappings":";;;;+BAmFgBA;;;eAAAA;;;6BAzET;AAEP,MAAMC,gCAAgCC,IAAAA,iBAAI,EAAC;IACzCC,yBAAyBC,IAAAA,qBAAQ,EAACC,IAAAA,mBAAM;IACxCC,cAAcF,IAAAA,qBAAQ,EAACC,IAAAA,mBAAM;IAC7BE,WAAWC,IAAAA,sBAAS,EAACC,IAAAA,oBAAO,KAAI;IAEhCC,QAAQF,IAAAA,sBAAS,EACfG,IAAAA,mBAAM,EAAC;QACLC,SAASJ,IAAAA,sBAAS,EAACC,IAAAA,oBAAO,KAAI;QAC9BI,MAAML,IAAAA,sBAAS,EAACM,IAAAA,mBAAM,KAAI;QAC1BC,MAAMP,IAAAA,sBAAS,EAACH,IAAAA,mBAAM,KAAIW,QAAQC,GAAG;IACvC,IACA,CAAC;IAGHC,SAASV,IAAAA,sBAAS,EAChBG,IAAAA,mBAAM,EAAC;QACLQ,UAAUX,IAAAA,sBAAS,EAACC,IAAAA,oBAAO,KAAI;IACjC,IACA,CAAC;AAEL;AAmDO,SAAST,WAAWoB,sBAA+C;IACxE,OAAOC,IAAAA,mBAAM,EAACD,wBAAwBnB;AACxC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Setup file for Jest. This file is used in the Jest preset configuration, and
|
|
2
|
+
// not intended to be exported or used directly.
|
|
3
|
+
// eslint-disable-next-line import/no-unassigned-import
|
|
4
|
+
"use strict";
|
|
5
|
+
Object.defineProperty(exports, "__esModule", {
|
|
6
|
+
value: true
|
|
7
|
+
});
|
|
8
|
+
require("./matchers");
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=setup.js.map
|
|
@@ -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;;;;;QAChD"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "NotificationType", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return _rpcmethods.NotificationType;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
const _rpcmethods = require("@metamask/rpc-methods");
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -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":";;;;+BA2SSA;;;eAAAA,4BAAgB;;;4BAAQ"}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
function _check_private_redeclaration(obj, privateCollection) {
|
|
2
|
+
if (privateCollection.has(obj)) {
|
|
3
|
+
throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
4
|
+
}
|
|
5
|
+
}
|
|
6
|
+
function _class_apply_descriptor_get(receiver, descriptor) {
|
|
7
|
+
if (descriptor.get) {
|
|
8
|
+
return descriptor.get.call(receiver);
|
|
9
|
+
}
|
|
10
|
+
return descriptor.value;
|
|
11
|
+
}
|
|
12
|
+
function _class_apply_descriptor_set(receiver, descriptor, value) {
|
|
13
|
+
if (descriptor.set) {
|
|
14
|
+
descriptor.set.call(receiver, value);
|
|
15
|
+
} else {
|
|
16
|
+
if (!descriptor.writable) {
|
|
17
|
+
throw new TypeError("attempted to set read only private field");
|
|
18
|
+
}
|
|
19
|
+
descriptor.value = value;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function _class_extract_field_descriptor(receiver, privateMap, action) {
|
|
23
|
+
if (!privateMap.has(receiver)) {
|
|
24
|
+
throw new TypeError("attempted to " + action + " private field on non-instance");
|
|
25
|
+
}
|
|
26
|
+
return privateMap.get(receiver);
|
|
27
|
+
}
|
|
28
|
+
function _class_private_field_get(receiver, privateMap) {
|
|
29
|
+
var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
|
|
30
|
+
return _class_apply_descriptor_get(receiver, descriptor);
|
|
31
|
+
}
|
|
32
|
+
function _class_private_field_init(obj, privateMap, value) {
|
|
33
|
+
_check_private_redeclaration(obj, privateMap);
|
|
34
|
+
privateMap.set(obj, value);
|
|
35
|
+
}
|
|
36
|
+
function _class_private_field_set(receiver, privateMap, value) {
|
|
37
|
+
var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
|
|
38
|
+
_class_apply_descriptor_set(receiver, descriptor, value);
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function _define_property(obj, key, value) {
|
|
42
|
+
if (key in obj) {
|
|
43
|
+
Object.defineProperty(obj, key, {
|
|
44
|
+
value: value,
|
|
45
|
+
enumerable: true,
|
|
46
|
+
configurable: true,
|
|
47
|
+
writable: true
|
|
48
|
+
});
|
|
49
|
+
} else {
|
|
50
|
+
obj[key] = value;
|
|
51
|
+
}
|
|
52
|
+
return obj;
|
|
53
|
+
}
|
|
54
|
+
import { assert, createModuleLogger } from '@metamask/utils';
|
|
55
|
+
import NodeEnvironment from 'jest-environment-node';
|
|
56
|
+
import { remote } from 'webdriverio';
|
|
57
|
+
import { rootLogger, startServer } from './internals';
|
|
58
|
+
import { getOptions } from './options';
|
|
59
|
+
/* eslint-enable */ const log = createModuleLogger(rootLogger, 'environment');
|
|
60
|
+
var _options = /*#__PURE__*/ new WeakMap(), _server = /*#__PURE__*/ new WeakMap();
|
|
61
|
+
export class SnapsEnvironment extends NodeEnvironment {
|
|
62
|
+
/**
|
|
63
|
+
* Set up the environment. This starts the built-in HTTP server, and creates a
|
|
64
|
+
* new browser instance.
|
|
65
|
+
*/ async setup() {
|
|
66
|
+
await super.setup();
|
|
67
|
+
if (_class_private_field_get(this, _options).server.enabled) {
|
|
68
|
+
log('Starting server.');
|
|
69
|
+
_class_private_field_set(this, _server, await startServer(_class_private_field_get(this, _options).server));
|
|
70
|
+
}
|
|
71
|
+
const args = [];
|
|
72
|
+
if (_class_private_field_get(this, _options).browser.headless) {
|
|
73
|
+
args.push('--headless', '--disable-gpu');
|
|
74
|
+
}
|
|
75
|
+
log('Starting browser.');
|
|
76
|
+
this.browser = await remote({
|
|
77
|
+
logLevel: 'error',
|
|
78
|
+
capabilities: {
|
|
79
|
+
browserName: 'chrome',
|
|
80
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
81
|
+
'goog:chromeOptions': {
|
|
82
|
+
args
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
this.global.browser = this.browser;
|
|
87
|
+
this.global.snapsEnvironment = this;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Tear down the environment. This closes the browser, and stops the built-in
|
|
91
|
+
* HTTP server.
|
|
92
|
+
*/ async teardown() {
|
|
93
|
+
if (_class_private_field_get(this, _options).keepAlive) {
|
|
94
|
+
log('Not tearing down environment because keepAlive is enabled.');
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
log('Closing browser, and stopping server.');
|
|
98
|
+
await this.browser?.deleteSession();
|
|
99
|
+
_class_private_field_get(this, _server)?.close();
|
|
100
|
+
await super.teardown();
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Get the URL to the simulator, including the environment URL.
|
|
104
|
+
*
|
|
105
|
+
* @returns The simulator URL.
|
|
106
|
+
* @throws If the server is not running.
|
|
107
|
+
*/ get url() {
|
|
108
|
+
assert(_class_private_field_get(this, _server), 'Server is not running.');
|
|
109
|
+
const { port } = _class_private_field_get(this, _server).address();
|
|
110
|
+
const simulatorUrl = _class_private_field_get(this, _options).simulatorUrl ?? `http://localhost:${port}/simulator/`;
|
|
111
|
+
const executionEnvironmentUrl = _class_private_field_get(this, _options).executionEnvironmentUrl ?? `http://localhost:${port}/environment/`;
|
|
112
|
+
return `${simulatorUrl}?environment=${encodeURIComponent(executionEnvironmentUrl)}`;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Get the snap ID for the current environment, which is used if no snap ID is
|
|
116
|
+
* passed to {@link installSnap}. This assumes that the built-in server is
|
|
117
|
+
* running.
|
|
118
|
+
*
|
|
119
|
+
* @returns The snap ID.
|
|
120
|
+
* @throws If the server is not running.
|
|
121
|
+
*/ get snapId() {
|
|
122
|
+
assert(_class_private_field_get(this, _server), 'You must specify a snap ID, because the built-in server is not running.');
|
|
123
|
+
const { port } = _class_private_field_get(this, _server).address();
|
|
124
|
+
return `local:http://localhost:${port}`;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Create a new page, and attach logging handlers.
|
|
128
|
+
*
|
|
129
|
+
* @param url - The page URL. Defaults to the specified Snaps Simulator URL,
|
|
130
|
+
* or the default simulator URL if none is specified.
|
|
131
|
+
* @param timeout - The page timeout, in milliseconds.
|
|
132
|
+
* @returns The new page.
|
|
133
|
+
*/ async createPage(url = this.url, timeout = 10000) {
|
|
134
|
+
const puppeteer = await this.browser.getPuppeteer();
|
|
135
|
+
const page = await puppeteer.newPage();
|
|
136
|
+
page.setDefaultTimeout(timeout);
|
|
137
|
+
page.setDefaultNavigationTimeout(timeout);
|
|
138
|
+
// Give the page permission to show notifications. This is required for
|
|
139
|
+
// testing `snap_notify`.
|
|
140
|
+
await page.browserContext().overridePermissions(url, [
|
|
141
|
+
'notifications'
|
|
142
|
+
]);
|
|
143
|
+
// `networkidle0` is used to ensure that the page is fully loaded. This
|
|
144
|
+
// makes it wait for no requests to be made, which guarantees that the page
|
|
145
|
+
// is ready.
|
|
146
|
+
await page.goto(url, {
|
|
147
|
+
waitUntil: 'networkidle0'
|
|
148
|
+
});
|
|
149
|
+
const browserLog = createModuleLogger(rootLogger, 'browser');
|
|
150
|
+
page// This is fired when the page calls `console.log` or similar.
|
|
151
|
+
.on('console', (message)=>{
|
|
152
|
+
browserLog(`[${message.type()}] ${message.text()}`);
|
|
153
|
+
})// This is fired when the page throws an error.
|
|
154
|
+
.on('pageerror', ({ message })=>{
|
|
155
|
+
browserLog(`[page error] ${message}`);
|
|
156
|
+
});
|
|
157
|
+
return page;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Constructor.
|
|
161
|
+
*
|
|
162
|
+
* @param options - The environment options.
|
|
163
|
+
* @param context - The environment context.
|
|
164
|
+
*/ constructor(options, context){
|
|
165
|
+
super(options, context);
|
|
166
|
+
// `browser` is always set in the environment setup function. To avoid needing
|
|
167
|
+
// to check for `undefined` everywhere, we use a type assertion here.
|
|
168
|
+
_define_property(this, "browser", void 0);
|
|
169
|
+
_class_private_field_init(this, _options, {
|
|
170
|
+
writable: true,
|
|
171
|
+
value: void 0
|
|
172
|
+
});
|
|
173
|
+
_class_private_field_init(this, _server, {
|
|
174
|
+
writable: true,
|
|
175
|
+
value: void 0
|
|
176
|
+
});
|
|
177
|
+
_class_private_field_set(this, _options, getOptions(options.projectConfig.testEnvironmentOptions));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
export default SnapsEnvironment;
|
|
181
|
+
|
|
182
|
+
//# sourceMappingURL=environment.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/environment.ts"],"sourcesContent":["import { EnvironmentContext, JestEnvironmentConfig } from '@jest/environment';\nimport { assert, createModuleLogger } from '@metamask/utils';\nimport { Server } from 'http';\nimport NodeEnvironment from 'jest-environment-node';\nimport { AddressInfo } from 'net';\nimport { Browser } from 'puppeteer';\nimport { remote } from 'webdriverio';\n\nimport { rootLogger, startServer } from './internals';\nimport { getOptions, SnapsEnvironmentOptions } from './options';\n\n/* eslint-disable */\ndeclare global {\n const browser: WebdriverIO.Browser;\n const snapsEnvironment: SnapsEnvironment;\n}\n/* eslint-enable */\n\nconst log = createModuleLogger(rootLogger, 'environment');\n\nexport class SnapsEnvironment extends NodeEnvironment {\n // `browser` is always set in the environment setup function. To avoid needing\n // to check for `undefined` everywhere, we use a type assertion here.\n browser!: WebdriverIO.Browser;\n\n #options: SnapsEnvironmentOptions;\n\n #server: Server | undefined;\n\n /**\n * Constructor.\n *\n * @param options - The environment options.\n * @param context - The environment context.\n */\n constructor(options: JestEnvironmentConfig, context: EnvironmentContext) {\n super(options, context);\n this.#options = getOptions(options.projectConfig.testEnvironmentOptions);\n }\n\n /**\n * Set up the environment. This starts the built-in HTTP server, and creates a\n * new browser instance.\n */\n async setup() {\n await super.setup();\n\n if (this.#options.server.enabled) {\n log('Starting server.');\n this.#server = await startServer(this.#options.server);\n }\n\n const args = [];\n if (this.#options.browser.headless) {\n args.push('--headless', '--disable-gpu');\n }\n\n log('Starting browser.');\n this.browser = await remote({\n logLevel: 'error',\n capabilities: {\n browserName: 'chrome',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'goog:chromeOptions': {\n args,\n },\n },\n });\n\n this.global.browser = this.browser;\n this.global.snapsEnvironment = this;\n }\n\n /**\n * Tear down the environment. This closes the browser, and stops the built-in\n * HTTP server.\n */\n async teardown() {\n if (this.#options.keepAlive) {\n log('Not tearing down environment because keepAlive is enabled.');\n return;\n }\n\n log('Closing browser, and stopping server.');\n await this.browser?.deleteSession();\n this.#server?.close();\n\n await super.teardown();\n }\n\n /**\n * Get the URL to the simulator, including the environment URL.\n *\n * @returns The simulator URL.\n * @throws If the server is not running.\n */\n get url() {\n assert(this.#server, 'Server is not running.');\n\n const { port } = this.#server.address() as AddressInfo;\n const simulatorUrl =\n this.#options.simulatorUrl ?? `http://localhost:${port}/simulator/`;\n\n const executionEnvironmentUrl =\n this.#options.executionEnvironmentUrl ??\n `http://localhost:${port}/environment/`;\n\n return `${simulatorUrl}?environment=${encodeURIComponent(\n executionEnvironmentUrl,\n )}`;\n }\n\n /**\n * Get the snap ID for the current environment, which is used if no snap ID is\n * passed to {@link installSnap}. This assumes that the built-in server is\n * running.\n *\n * @returns The snap ID.\n * @throws If the server is not running.\n */\n get snapId() {\n assert(\n this.#server,\n 'You must specify a snap ID, because the built-in server is not running.',\n );\n\n const { port } = this.#server.address() as AddressInfo;\n return `local:http://localhost:${port}`;\n }\n\n /**\n * Create a new page, and attach logging handlers.\n *\n * @param url - The page URL. Defaults to the specified Snaps Simulator URL,\n * or the default simulator URL if none is specified.\n * @param timeout - The page timeout, in milliseconds.\n * @returns The new page.\n */\n async createPage(url: string = this.url, timeout = 10000) {\n const puppeteer = (await this.browser.getPuppeteer()) as unknown as Browser;\n const page = await puppeteer.newPage();\n\n page.setDefaultTimeout(timeout);\n page.setDefaultNavigationTimeout(timeout);\n\n // Give the page permission to show notifications. This is required for\n // testing `snap_notify`.\n await page.browserContext().overridePermissions(url, ['notifications']);\n\n // `networkidle0` is used to ensure that the page is fully loaded. This\n // makes it wait for no requests to be made, which guarantees that the page\n // is ready.\n await page.goto(url, { waitUntil: 'networkidle0' });\n\n const browserLog = createModuleLogger(rootLogger, 'browser');\n\n page\n // This is fired when the page calls `console.log` or similar.\n .on('console', (message) => {\n browserLog(`[${message.type()}] ${message.text()}`);\n })\n\n // This is fired when the page throws an error.\n .on('pageerror', ({ message }) => {\n browserLog(`[page error] ${message}`);\n });\n\n return page;\n }\n}\n\nexport default SnapsEnvironment;\n"],"names":["assert","createModuleLogger","NodeEnvironment","remote","rootLogger","startServer","getOptions","log","SnapsEnvironment","setup","options","server","enabled","args","browser","headless","push","logLevel","capabilities","browserName","global","snapsEnvironment","teardown","keepAlive","deleteSession","close","url","port","address","simulatorUrl","executionEnvironmentUrl","encodeURIComponent","snapId","createPage","timeout","puppeteer","getPuppeteer","page","newPage","setDefaultTimeout","setDefaultNavigationTimeout","browserContext","overridePermissions","goto","waitUntil","browserLog","on","message","type","text","constructor","context","projectConfig","testEnvironmentOptions"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,MAAM,EAAEC,kBAAkB,QAAQ,kBAAkB;AAE7D,OAAOC,qBAAqB,wBAAwB;AAGpD,SAASC,MAAM,QAAQ,cAAc;AAEr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B,8EAA8E;QAC9E,qEAAqE;QACrErC,uBAAAA,WAAAA,KAAAA;QAEA,gCAAA;;mBAAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;uCAUQJ,UAAUJ,WAAWI,QAAQ0C,aAAa,CAACC,sBAAsB;IACzE;AAmIF;AAEA,eAAe7C,iBAAiB"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createModuleLogger } from '@metamask/utils';
|
|
2
|
+
import { getDocument, queries } from 'pptr-testing-library';
|
|
3
|
+
import { getEnvironment, mock, waitFor, request, sendTransaction, runCronjob, mockJsonRpc, rootLogger } from './internals';
|
|
4
|
+
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
5
|
+
const { getByTestId } = queries;
|
|
6
|
+
const log = createModuleLogger(rootLogger, 'helpers');
|
|
7
|
+
/**
|
|
8
|
+
* Load a snap into the environment. This is the main entry point for testing
|
|
9
|
+
* snaps: It returns a {@link Snap} object that can be used to interact with the
|
|
10
|
+
* snap.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { installSnap } from '@metamask/snaps-jest';
|
|
15
|
+
*
|
|
16
|
+
* describe('My Snap', () => {
|
|
17
|
+
* it('should do something', async () => {
|
|
18
|
+
* const { request } = await installSnap('local:my-snap');
|
|
19
|
+
* const response = await request({
|
|
20
|
+
* method: 'foo',
|
|
21
|
+
* params: ['bar'],
|
|
22
|
+
* });
|
|
23
|
+
* expect(response).toRespondWith('bar');
|
|
24
|
+
* });
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
* @param snapId - The ID of the snap, including the prefix (`local:`). Defaults
|
|
28
|
+
* to the URL of the built-in server, if it is running. This supports both
|
|
29
|
+
* local snap IDs and NPM snap IDs.
|
|
30
|
+
* @returns The snap.
|
|
31
|
+
* @throws If the built-in server is not running, and no snap ID is provided.
|
|
32
|
+
*/ export async function installSnap(snapId = getEnvironment().snapId) {
|
|
33
|
+
const environment = getEnvironment();
|
|
34
|
+
log('Installing snap %s.', snapId);
|
|
35
|
+
const page = await environment.createPage();
|
|
36
|
+
const document = await getDocument(page);
|
|
37
|
+
log('Setting snap ID to %s.', snapId);
|
|
38
|
+
await page.evaluate((payload)=>{
|
|
39
|
+
window.__SIMULATOR_API__.dispatch({
|
|
40
|
+
type: 'configuration/setSnapId',
|
|
41
|
+
payload
|
|
42
|
+
});
|
|
43
|
+
}, snapId);
|
|
44
|
+
log('Waiting for snap to install.');
|
|
45
|
+
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
46
|
+
await waitFor(async ()=>await getByTestId(document, 'status-ok'), {
|
|
47
|
+
timeout: 10000,
|
|
48
|
+
message: `Timed out waiting for snap to install. Make sure the snap ID ("${snapId}") is correct, and the server is running.`
|
|
49
|
+
});
|
|
50
|
+
return {
|
|
51
|
+
request: (options)=>{
|
|
52
|
+
log('Sending request %o.', options);
|
|
53
|
+
// Note: This function is intentionally not async, so that we can access
|
|
54
|
+
// the `getInterface` method on the response.
|
|
55
|
+
return request(page, options);
|
|
56
|
+
},
|
|
57
|
+
sendTransaction: async (options = {})=>{
|
|
58
|
+
log('Sending transaction %o.', options);
|
|
59
|
+
return await sendTransaction(page, options);
|
|
60
|
+
},
|
|
61
|
+
runCronjob: (options)=>{
|
|
62
|
+
log('Running cronjob %o.', options);
|
|
63
|
+
// Note: This function is intentionally not async, so that we can access
|
|
64
|
+
// the `getInterface` method on the response.
|
|
65
|
+
return runCronjob(page, options);
|
|
66
|
+
},
|
|
67
|
+
close: async ()=>{
|
|
68
|
+
log('Closing page.');
|
|
69
|
+
await page.close();
|
|
70
|
+
},
|
|
71
|
+
mock: async (options)=>{
|
|
72
|
+
log('Mocking %o.', options);
|
|
73
|
+
return await mock(page, options);
|
|
74
|
+
},
|
|
75
|
+
mockJsonRpc: async (options)=>{
|
|
76
|
+
log('Mocking JSON-RPC %o.', options);
|
|
77
|
+
return await mockJsonRpc(page, options);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/helpers.ts"],"sourcesContent":["import { createModuleLogger } from '@metamask/utils';\nimport { getDocument, queries } from 'pptr-testing-library';\n\nimport {\n getEnvironment,\n mock,\n waitFor,\n request,\n sendTransaction,\n runCronjob,\n mockJsonRpc,\n rootLogger,\n} from './internals';\nimport type { Snap, SnapResponse } from './types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst { getByTestId } = queries;\n\nconst log = createModuleLogger(rootLogger, 'helpers');\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * ```ts\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * ```\n * @param snapId - The ID of the snap, including the prefix (`local:`). Defaults\n * to the URL of the built-in server, if it is running. This supports both\n * local snap IDs and NPM snap IDs.\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap(\n snapId: string = getEnvironment().snapId,\n): Promise<Snap> {\n const environment = getEnvironment();\n\n log('Installing snap %s.', snapId);\n\n const page = await environment.createPage();\n const document = await getDocument(page);\n\n log('Setting snap ID to %s.', snapId);\n await page.evaluate((payload) => {\n window.__SIMULATOR_API__.dispatch({\n type: 'configuration/setSnapId',\n payload,\n });\n }, snapId);\n\n log('Waiting for snap to install.');\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n await waitFor(async () => await getByTestId(document, 'status-ok'), {\n timeout: 10000,\n message: `Timed out waiting for snap to install. Make sure the snap ID (\"${snapId}\") is correct, and the server is running.`,\n });\n\n return {\n request: (options) => {\n log('Sending request %o.', options);\n\n // Note: This function is intentionally not async, so that we can access\n // the `getInterface` method on the response.\n return request(page, options);\n },\n\n sendTransaction: async (options = {}): Promise<SnapResponse> => {\n log('Sending transaction %o.', options);\n\n return await sendTransaction(page, options);\n },\n\n runCronjob: (options) => {\n log('Running cronjob %o.', options);\n\n // Note: This function is intentionally not async, so that we can access\n // the `getInterface` method on the response.\n return runCronjob(page, options);\n },\n\n close: async () => {\n log('Closing page.');\n\n await page.close();\n },\n\n mock: async (options) => {\n log('Mocking %o.', options);\n\n return await mock(page, options);\n },\n\n mockJsonRpc: async (options) => {\n log('Mocking JSON-RPC %o.', options);\n\n return await mockJsonRpc(page, options);\n },\n };\n}\n"],"names":["createModuleLogger","getDocument","queries","getEnvironment","mock","waitFor","request","sendTransaction","runCronjob","mockJsonRpc","rootLogger","getByTestId","log","installSnap","snapId","environment","page","createPage","document","evaluate","payload","window","__SIMULATOR_API__","dispatch","type","timeout","message","options","close"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,kBAAkB;AACrD,SAASC,WAAW,EAAEC,OAAO,QAAQ,uBAAuB;AAE5D,SACEC,cAAc,EACdC,IAAI,EACJC,OAAO,EACPC,OAAO,EACPC,eAAe,EACfC,UAAU,EACVC,WAAW,EACXC,UAAU,QACL,cAAc;AAGrB,6DAA6D;AAC7D,MAAM,EAAEC,WAAW,EAAE,GAAGT;AAExB,MAAMU,MAAMZ,mBAAmBU,YAAY;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,eAAeG,YACpBC,SAAiBX,iBAAiBW,MAAM;IAExC,MAAMC,cAAcZ;IAEpBS,IAAI,uBAAuBE;IAE3B,MAAME,OAAO,MAAMD,YAAYE,UAAU;IACzC,MAAMC,WAAW,MAAMjB,YAAYe;IAEnCJ,IAAI,0BAA0BE;IAC9B,MAAME,KAAKG,QAAQ,CAAC,CAACC;QACnBC,OAAOC,iBAAiB,CAACC,QAAQ,CAAC;YAChCC,MAAM;YACNJ;QACF;IACF,GAAGN;IAEHF,IAAI;IACJ,kEAAkE;IAClE,MAAMP,QAAQ,UAAY,MAAMM,YAAYO,UAAU,cAAc;QAClEO,SAAS;QACTC,SAAS,CAAC,+DAA+D,EAAEZ,OAAO,yCAAyC,CAAC;IAC9H;IAEA,OAAO;QACLR,SAAS,CAACqB;YACRf,IAAI,uBAAuBe;YAE3B,wEAAwE;YACxE,6CAA6C;YAC7C,OAAOrB,QAAQU,MAAMW;QACvB;QAEApB,iBAAiB,OAAOoB,UAAU,CAAC,CAAC;YAClCf,IAAI,2BAA2Be;YAE/B,OAAO,MAAMpB,gBAAgBS,MAAMW;QACrC;QAEAnB,YAAY,CAACmB;YACXf,IAAI,uBAAuBe;YAE3B,wEAAwE;YACxE,6CAA6C;YAC7C,OAAOnB,WAAWQ,MAAMW;QAC1B;QAEAC,OAAO;YACLhB,IAAI;YAEJ,MAAMI,KAAKY,KAAK;QAClB;QAEAxB,MAAM,OAAOuB;YACXf,IAAI,eAAee;YAEnB,OAAO,MAAMvB,KAAKY,MAAMW;QAC1B;QAEAlB,aAAa,OAAOkB;YAClBf,IAAI,wBAAwBe;YAE5B,OAAO,MAAMlB,YAAYO,MAAMW;QACjC;IACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export { default, default as TestEnvironment } from './environment';\nexport * from './helpers';\nexport * from './options';\nexport * from './types';\n"],"names":["default","TestEnvironment"],"mappings":"AAAA,SAASA,OAAO,EAAEA,WAAWC,eAAe,QAAQ,gBAAgB;AACpE,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,UAAU"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { assert } from '@metamask/utils';
|
|
2
|
+
/**
|
|
3
|
+
* Get the Snaps environment. This asserts that the environment has been
|
|
4
|
+
* configured.
|
|
5
|
+
*
|
|
6
|
+
* @returns The Snaps environment.
|
|
7
|
+
*/ export function getEnvironment() {
|
|
8
|
+
// `snapsEnvironment` is a global variable that is set by the Jest
|
|
9
|
+
// environment.
|
|
10
|
+
assert(snapsEnvironment, 'Snaps environment not found. Make sure you have configured the environment correctly.');
|
|
11
|
+
return snapsEnvironment;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=environment.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/environment.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\n/**\n * Get the Snaps environment. This asserts that the environment has been\n * configured.\n *\n * @returns The Snaps environment.\n */\nexport function getEnvironment() {\n // `snapsEnvironment` is a global variable that is set by the Jest\n // environment.\n assert(\n snapsEnvironment,\n 'Snaps environment not found. Make sure you have configured the environment correctly.',\n );\n\n return snapsEnvironment;\n}\n"],"names":["assert","getEnvironment","snapsEnvironment"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC;;;;;CAKC,GACD,OAAO,SAASC;IACd,kEAAkE;IAClE,eAAe;IACfD,OACEE,kBACA;IAGF,OAAOA;AACT"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './environment';
|
|
2
|
+
export * from './interface';
|
|
3
|
+
export * from './logger';
|
|
4
|
+
export * from './network';
|
|
5
|
+
export * from './request';
|
|
6
|
+
export * from './server';
|
|
7
|
+
export * from './structs';
|
|
8
|
+
// eslint-disable-next-line import/export
|
|
9
|
+
export * from './types';
|
|
10
|
+
export * from './wait-for';
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/index.ts"],"sourcesContent":["export * from './environment';\nexport * from './interface';\nexport * from './logger';\nexport * from './network';\nexport * from './request';\nexport * from './server';\nexport * from './structs';\n// eslint-disable-next-line import/export\nexport * from './types';\nexport * from './wait-for';\n"],"names":[],"mappings":"AAAA,cAAc,gBAAgB;AAC9B,cAAc,cAAc;AAC5B,cAAc,WAAW;AACzB,cAAc,YAAY;AAC1B,cAAc,YAAY;AAC1B,cAAc,WAAW;AACzB,cAAc,YAAY;AAC1B,yCAAyC;AACzC,cAAc,UAAU;AACxB,cAAc,aAAa"}
|