Skip to content

Commit

Permalink
fix: improve types for mock and allow event listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
drusco committed Mar 15, 2024
1 parent ece00ad commit efb6cd0
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
1 change: 1 addition & 0 deletions src/handlers/apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const apply = (mock: Nexo.Mock, that: unknown, args: unknown[]): unknown => {
const event = new ProxyHandlerEvent("apply", proxy, { that, args });

scope.emit(event.name, event);
mock.emit(event.name, event);

if (event.defaultPrevented) {
return event.returnValue;
Expand Down
8 changes: 4 additions & 4 deletions src/types/Nexo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Nexo from "../Nexo.js";
import EventEmitter from "node:events";

declare namespace Nexo {
type functionLike = (...args: unknown[]) => unknown;
Expand All @@ -13,13 +14,12 @@ declare namespace Nexo {
proxyMap: Map<string, WeakRef<Proxy>>;
};

interface Mock extends functionLike {}

interface Proxy extends Mock {
interface Mock extends EventEmitter {
(...args: unknown[]): unknown;
[K: objectKey]: unknown;
}

interface Proxy extends functionLike {}

namespace proxy {
type data = {
id: string;
Expand Down
6 changes: 5 additions & 1 deletion src/utils/getProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import map from "./map.js";
import findProxy from "./findProxy.js";
import isTraceable from "./isTraceable.js";
import handlers from "../handlers/index.js";
import EventEmitter from "node:events";

const getProxy = (scope: Nexo, target: Nexo.traceable | void): Nexo.Proxy => {
// find proxy by target
Expand All @@ -18,7 +19,10 @@ const getProxy = (scope: Nexo, target: Nexo.traceable | void): Nexo.Proxy => {
const traceable = isTraceable(target);
const data: Nexo.data = map.emulators.get(scope);
const { proxyMap } = data;
const mock: Nexo.Mock = function () {};
const mock: Nexo.Mock = Object.setPrototypeOf(
function () {},
EventEmitter.prototype,
);
const proxy = new Proxy(mock, handlers) as Nexo.Proxy;

// set information about this proxy
Expand Down

0 comments on commit efb6cd0

Please sign in to comment.