A step by step guide that shows how to serialize and deserialize an object with a date (
It will also work for other complex type
) when using the puppeteer evaluate function.
This is the example object that has a date property that we will pass to the browser.
let dayObj = {
"name": "saturday",
"date": new Date(2020, 1, 25)
}
From and to the evaluate function, you need to pass a serialized object (ie object that are stringified).
let dayJson = JSON.stringify(dayObj);
console.log(dayJson);
{"name":"saturday","date":"2020-02-24T23:00:00.000Z"}"
We have string, we can pass it to the evaluate function and return any other object back by serializing it (ie stringified)
let dayJsonFromBrowser = await page.evaluate((dayJsonInBrowser) => {
// To make it an object back, you can parse it
let dayObjInBrowser = JSON.parse(dayJsonInBrowser);
// And pass it back again with stringify
return JSON.stringify(dayObjInBrowser);
}, dayJson);
After receiving a serialized object back from the evaluate function, you need to rebuild it with the JSON.parse function and a reviver function. The reviver get as arguments, the key and the value of each property of the object and this is where you can build the object back as a date.
let dayObjFromBrowser = JSON.parse(dayJsonFromBrowser, (key, value) => {
// The key of the properties
if (key == 'date') {
// if the name of the properties is date, deserialize it (ie make it a date)
return new Date(value);
} else {
return value;
}
})
expect(dayObj).toEqual(dayObjFromBrowser);
PASS
If you have an object with a function, you can cast the object to its original type with the Object.assign function.
Example:
class day {
name: string;
date: Date;
constructor(name: string, date: Date){
this.name = name;
this.date = date;
}
getDate(){
return this.date;
}
}
const dummObject = new day("", new Date());
let dayType = Object.assign(dummObject, dayObjFromBrowser);
// jest assertion
expect(dayType.getDate()).toEqual(new Date(2020, 1, 25));
PASS