Snapshot shows timezone name instead of GMT code in CI server - javascript

I'm using a snapshot test in my project and came across a weird problem when running this specific test on a CI server: it displays the timezone name instead of the GMT code, causing the test failure.
I have tried using "moment-timezone" and Date.UTC() to normalize the dates, the result shown was the correct date with the same issue as above.
I've also tried to stub the global.Date object, but the components complained about prop incompatibility.
it('should render with props', () => {
const order = {
merchant: { logo: 'abc', name: 'Pizza Hut' },
bag: {
items: [{ name: 'Corn & Bacon' }],
total: {
valueWithDiscount: 99.99,
},
},
delivery: {
deliversAt: new Date('2019-05-21 13:00'),
},
payment: {
mode: 'online',
},
lastStatus: API_STATUSES.cancelled,
createdAt: new Date('2019-05-21 12:00'),
details: {},
};
const wrapper = shallowMount(Order, {
...commons,
propsData: { order },
});
expect(wrapper).toMatchSnapshot();
});
See that the expected date is the same as the received one, but syntactic differences:
<div class="order__details">
- <orderdetails-stub paymentmode="online" deliverytime="Fri Jun 21 2019 10:00:00 GMT-0300 (GMT-03:00)" value="99.99" laststatus="cancelled"></orderdetails-stub>
+ <orderdetails-stub paymentmode="online" deliverytime="Fri Jun 21 2019 10:00:00 GMT-0300 (Brasilia Standard Time)" value="99.99" laststatus="cancelled"></orderdetails-stub>

Using Date strings as props like this is hazardous and likely to lead to the sort of problem you're encountering.
Best practice for tests in my experience is to use Date.getTime() so values are numbers of milliseconds without any locale information.
Alternatively, you can use moment-timezone as described in this article:
import moment from 'moment-timezone';
it('renders without crashing', () => {
moment.tz.setDefault('EST');
let props = {
currentDay: moment("2017-09-15 09:30:00").format("MMM Do YYYY h:mm:ss a")
};
const tree = renderer.create(<App {...props} />).toJSON();
expect(tree).toMatchSnapshot();
});

Related

State Variable not being correctly captured, when passing through components

I have excluded some parts of my original code for readability, sorry if it causes any confusion!
I have a state variable in App.js defined as such
const [tasks, setTasks] = useState([])
From App.js, I pass into Tasks.js the state variable as a
prop.
Tasks.js receives the prop and sorts it as below (when a certain button is clicked)
const Tasks = function ({tasks, setTasks}) {
setTasks(tasks.sort((a, b) => {
if ((moment(a.isoDay).unix()) < (moment(b.isoDay).unix())) return -1
else {
return 0
}
}))
}
This causes the state variable in App.js to be updated, and this state variable is
passed into Calendar.js (from App.js) as a prop as well, as seen below
const Calendar = ({tasks}) => {
function TaskToCalendar(tasks) {
console.log(tasks)
console.log(tasks[0])
}
}
However, I am not accurately capturing the value of tasks.
For example, console.log(tasks) yields this before it is
sorted in Tasks.js
(2) [{…}, {…}]
0: {text: "Test0", day: "Tue Jun 01 2021"}
1: {text: "Test1", day: "Wed Jun 02 2021"}
and yields this after it is sorted in Tasks.js
(2) [{…}, {…}]
0: {text: "Test1", day: "Wed Jun 02 2021}
1: {text: "Test0", day: "Tue Jun 01 2021}
But, console.log(tasks[0]) yields this before and
after it is sorted
{text: "Test0", day: "Tue Jun 01 2021"}
I have to click on another button somewhere in my UI (that runs an unrelated function), for console.log(tasks[0]) to yield {text: "Test1", day: "Wed Jun 02 2021} after sorting.
How would I go about correctly passing the value of tasks, such that accessing the array indices gives me the correct values?
The SetTask function is working asynchronously. hence, this behavior.
For logging the value you can use the useeffect Hook

Mongoose not returning the correct number of results

I'm new to mongoose. I'm trying to query by createdAt date, with startDate and endDate, however I got the incorrect number of results.
data
{"_id":{"$oid":"5f4fab9beceaa20f898feafb"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Alex","email":"alex#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-02T14:26:35.237Z"},"updatedAt":{"$date":"2020-09-02T14:26:35.237Z"}}
{"_id":{"$oid":"5f4fc3677e7b1e2d806714cf"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Joshua","email":"joshua#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-02T16:08:07.123Z"},"updatedAt":{"$date":"2020-09-02T16:08:07.123Z"}}
{"_id":{"$oid":"5f50b80f28ca26065b2ac9a5"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Harold","email":"harold#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-03T09:31:59.112Z"},"updatedAt":{"$date":"2020-09-03T09:31:59.112Z"}}
{"_id":{"$oid":"5f59104ff518c40579b578d0"},"message":"Inquiry 101","service":"GENERAL_INQUIRY","name":"Katy","email":"katy#gmail.com","personalNumber":"0991898838398","createdAt":{"$date":"2020-09-09T17:26:39.787Z"},"updatedAt":{"$date":"2020-09-09T17:26:39.787Z"}}
I have 4 records with the ff. date 2020-09-02, 2020-09-03 and 2020-09-09
I wanted to get all records from 2020-09-02 and 2020-09-03, with these I expected 3 results as I have to records on the 2020-09-02, however I only got 2 results, those records have 2020-09-02 date with them.
const { limit = 30 } = params;
return new Promise((resolve, reject) => {
const query = {
createdAt: {
$gte: '2020-09-02',
$lte: '2020-09-03',
}
};
this.model.find(query).sort({
createdAt: 'descending',
}).limit(limit).exec((err, res) => {
if (!err) {
resolve(res);
}
reject(err);
})
})
Did I miss something with my code?
I also tried passing new Date('2020-09-02') but I still got same results.
I tried setting mongoose debug to true and below is what I got.
Mongoose: inquiries.find({ createdAt: { '$gte': new Date("Wed, 02
Sep 2020 00:00:00 GMT"), '$lte': new Date("Thu, 03 Sep 2020 00:00:00 GMT") }}, { sort: { createdAt: -1 }, limit: 30, projection: {}
})
Thanks in advance.
Youre looking for records greater than 2020-09-02 00:00:00 and less than 2020-09-03 00:00:00.
You only have 2 records which are between these values, if you want records including those at 2020-09-03 23:59:59, set your lte to 2020-09-04

Strange coercions of properties in asyncData in nuxt.js

I'm trying to play with asyncData in Nuxt.js and it seems to me that not every property could be placed here as is. For example instances of Moment (moment.js) and DateTime (luxon), they are serialized into string:
import { DateTime } from 'luxon'
const moment = require('moment')
...
asyncData(context) {
return {
date1: moment(),
date2: DateTime.local(),
pureDate: new Date()
}
},
mounted() {
console.log(typeof this.date1) // string ("2019-06-11T16:24:00.746Z")
console.log(typeof this.date2) // string ("2019-06-13T19:24:00.748+03:00")
console.log(typeof this.pureDate) // object (Thu Jun 13 2019 19:24:00 GMT+0300 (Moscow Standard Time))
}
some other complex objects properties raise warn:
Cannot stringify arbitrary non-POJOs OpenPositions
someone please explain me this behavior
sandbox snippet
demo repo on github

Moment js format date with timezone

Hi I am using Ember+moment.js to format date in my ember helpers.
I am getting the following date from the service
Tue Aug 23 2016 09:43:53 GMT+0200 (W. Europe Daylight Time)
In my ember helper class i am able to format date using following code :
var formattedDate = moment(date).format('DD/MM/YYYY h:mm a');
I am getting the following output :
23/08/2016 9:43 am
Expected Output : 23/08/2016 9:43 am GMT
How can i specify the timezone flag in the format function?
Any help should be appreciated.
Install ember-moment - ember install ember-moment
Install ember-cli-moment-shim - ember install ember-cli-moment-shim
stop and start ember server
To enable moment timezone, need to include moment:{ includeTimezone: 'all' } in config\environment.js
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'App-Name',
environment: environment,
baseURL: '/',
locationType: 'auto',
moment: {
// Options:
// 'all' - all years, all timezones
// '2010-2020' - 2010-2020, all timezones
// 'none' - no data, just timezone API
includeTimezone: 'all'
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
return ENV;
};
and then you can start use tz function and to get abbreviated time zone name you can include z flag in the format.
moment().tz('Asia/Calcutta').format('DD/MM/YYYY h:mm a z')

accessing mongodb's object from mapper (MapReduce)

I have an extra question based on the one I asked before:
calculate frequency using mongodb aggregate framework
so my data in MongoDB looks like this now:
{
"data": {
"interaction": {
"created_at": "Wed, 09 Apr 2014 14:38:16 +0000"
}
},
"_id": {
"$oid": "53455b59edcd5e4e3fdd4ebb"
}
}
before I used to have it like:
[
{
created_at: "2014-03-31T22:30:48.000Z",
id: 450762158586880000,
_id: "5339ec9808eb125965f2eae1"
}
]
so to access created_at I was using mapper like:
var mapper = function () {
if ( this.created_at.getTime() > ( last_date + 10000 ) ) {
...
but as the structure in my database has changed, I tried to change:
this.created_at.getTime()
to:
this.data.interaction.created_at.getTime()
but unfortunately it didn't work out. Thank you for any help
Hate to make this that simple but all you want to do when importing these date strings is this:
new Date("Wed, 09 Apr 2014 14:38:16 +0000")
Which will return a proper date type that you actually should be inserting as part of your data.

Categories