Skip to content

Quick Start Unit Test Example Didn't Work for Me (without modification) #678

@sjordan1975

Description

@sjordan1975

The sample code below is provided on Quick Start

function getTimeAgoDescription(dateString) {
	const startDate = new Date(dateString);
	const currentDate = new Date();

	const years = currentDate.getFullYear() - startDate.getFullYear();
	const months = currentDate.getMonth() - startDate.getMonth();
	const days = currentDate.getDate() - startDate.getDate();

	let timeAgoDescription = '';

	if (years > 0) {
		timeAgoDescription += `${years} ${years === 1 ? 'year' : 'years'}`;
	}

	if (months > 0) {
		if (timeAgoDescription !== '') {
			timeAgoDescription += ' ';
		}
		timeAgoDescription += `${months} ${months === 1 ? 'month' : 'months'}`;
	}

	if (days > 0) {
		if (timeAgoDescription !== '') {
			timeAgoDescription += ' ';
		}
		timeAgoDescription += `${days} ${days === 1 ? 'day' : 'days'}`;
	}

	if (timeAgoDescription === '') {
		timeAgoDescription = 'today';
	} else {
		timeAgoDescription += ' ago';
	}

	return timeAgoDescription;
}

Short version of the problem is that I never got the code to pass unit tests until I modified the code as follows (see comments about timezone):

function getTimeAgoDescription(dateString) {
	const startDate = new Date(dateString + 'T00:00:00'); // Add time to avoid timezone issues
	const currentDate = new Date();
         ...
}

Ironically, I reverted to good old Stackoverflow for the answer.

I say ironic because at no time and regardless of the amount of context or passing code into Cody Chat did it ever suggest the issue was js Date() defaults to UTC when passed a date string without a time/timezone. All the tests were failing (off by one day).

I would think this is exactly the kind of code assistance (pair programming) Cody is ideally suited for:

Cody: "Hey buddy, your intention is probably to get a date in your local timezone and if you pass only a date string, you'll get UTC instead.
Me: Thanks Cody, appreciate you got my back.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions