Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ export module DotNet {
* @throws Error if the given value is not an Object.
*/
export function createJSObjectReference(jsObject: any): any {
if (jsObject === null || jsObject === undefined) {
return {
[jsObjectIdKey]: -1
};
}

if (jsObject && (typeof jsObject === "object" || jsObject instanceof Function)) {
cachedJSObjectsById[nextJsObjectId] = new JSObject(jsObject);

Expand Down Expand Up @@ -220,7 +226,7 @@ export module DotNet {
export function disposeJSObjectReference(jsObjectReference: any): void {
const id = jsObjectReference && jsObjectReference[jsObjectIdKey];

if (typeof id === "number") {
if (typeof id === "number" && id !== -1) {
disposeJSObjectReferenceById(id);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,25 @@ describe("CallDispatcher", () => {

expect(result2).toBe("30");
});

test("createJSObjectReference: Handles null values without throwing", () => {
const nullRef = DotNet.createJSObjectReference(null);
expect(nullRef).toEqual({ [jsObjectId]: -1 });
});

test("createJSObjectReference: Handles undefined values without throwing", () => {
const undefinedRef = DotNet.createJSObjectReference(undefined);
expect(undefinedRef).toEqual({ [jsObjectId]: -1 });
});

test("disposeJSObjectReference: Safely handles null reference disposal", () => {
const nullRef = DotNet.createJSObjectReference(null);
expect(() => DotNet.disposeJSObjectReference(nullRef)).not.toThrow();
});

test("createJSObjectReference: Still throws for invalid types", () => {
expect(() => DotNet.createJSObjectReference("string")).toThrow();
expect(() => DotNet.createJSObjectReference(123)).toThrow();
expect(() => DotNet.createJSObjectReference(true)).toThrow();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ public override bool CanConvert(Type typeToConvert)
public override IJSObjectReference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var id = JSObjectReferenceJsonWorker.ReadJSObjectReferenceIdentifier(ref reader);

if (id == -1)
{
return null;
}

return new JSObjectReference(_jsRuntime, id);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,17 @@ public void Write_WritesValidJson()
// Assert
Assert.Equal($"{{\"__jsObjectId\":{jsObjectRef.Id}}}", json);
}

[Fact]
public void Read_ReturnsNull_WhenJSObjectIdIsMinusOne()
{
// Arrange
var json = "{\"__jsObjectId\":-1}";

// Act
var deserialized = JsonSerializer.Deserialize<IJSObjectReference>(json, JsonSerializerOptions);

// Assert
Assert.Null(deserialized);
}
}
Loading