Skip to content

Commit

Permalink
faking performance when it is not present throws
Browse files Browse the repository at this point in the history
  • Loading branch information
itayperry committed Sep 16, 2021
1 parent aaa8153 commit 227160c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
33 changes: 19 additions & 14 deletions src/fake-timers-src.js
Original file line number Diff line number Diff line change
Expand Up @@ -1525,20 +1525,6 @@ function withGlobal(_global) {

if (performancePresent) {
clock.performance = Object.create(null);

if (hasPerformancePrototype) {
const proto = _global.Performance.prototype;

Object.getOwnPropertyNames(proto).forEach(function (name) {
if (name.indexOf("getEntries") === 0) {
// match expected return type for getEntries functions
clock.performance[name] = NOOP_ARRAY;
} else {
clock.performance[name] = NOOP;
}
});
}

clock.performance.now = function FakeTimersNow() {
const hrt = hrtime();
const millis = hrt[0] * 1000 + hrt[1] / 1e6;
Expand Down Expand Up @@ -1613,6 +1599,25 @@ function withGlobal(_global) {
clock.attachedInterval = intervalId;
}

if (clock.methods.includes("performance")) {
if (hasPerformancePrototype) {
var proto = _global.Performance.prototype;
Object.getOwnPropertyNames(proto).forEach(function (name) {
if (name !== "now") {
clock.performance[name] =
name.indexOf("getEntries") === 0
? NOOP_ARRAY
: NOOP;
}
});
} else if (config.toFake.includes("performance")) {
// user explicitly tried to fake performance when not present
throw new ReferenceError(
"non-existent performance object cannot be faked"
);
}
}

for (i = 0, l = clock.methods.length; i < l; i++) {
const nameOfMethodToReplace = clock.methods[i];
if (nameOfMethodToReplace === "hrtime") {
Expand Down
15 changes: 15 additions & 0 deletions test/fake-timers-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3700,6 +3700,21 @@ describe("FakeTimers", function () {
});
}

if (!performanceNowPresent) {
it("throws when adding performance to tofake array when performance not present", function () {
try {
this.clock = FakeTimers.install({
toFake: ["performance"],
});
} catch (e) {
const expectedMsg =
"non-existent performance object cannot be faked";
assert(e instanceof ReferenceError);
assert.equals(e.message, expectedMsg);
}
});
}

if (performanceNowPresent) {
it("replaces global performance.now", function () {
this.clock = FakeTimers.install();
Expand Down

0 comments on commit 227160c

Please sign in to comment.