Writing Jest with ChatGPT
I’m new to ChatGPT. I have never create a GPT account.
Yesterday, I attended a ChatGPT Conference.
While implementing my new project at home, I thought it is possible to write test code by ChatGPT.
So I decided to try it and to write an article about the whole process.
Without Account(Free)
When I googled ChatGPT, I found a site named ChatGPT. I thought it is created by OpenAI, actually it is not an official site. However it isn’t required the account.
Visit ChatGPT and Press Try ChatGPT button.
I could see prompt to ask to ChatGPT.
Let’s see what I asked to him.
Me: Please create test code with jest for this code.
ChatGPT
Without the original code, it’s difficult to create accurate test code with Jest. However, here is an example of how to create a Jest test for a simple function that adds two numbers:
function addNumbers(a, b) {
return a + b;
}
test('adds two numbers', () => {
expect(addNumbers(2, 3)).toBe(5);
});
This test checks if the
addNumbers
function correctly adds two numbers and returns the expected result.
First, I asked to create test code with next code.
GPT answered the example how to create test code with example function.
Me
export const transformHolidayListItemToHoliday = (holidayItem: HolidayListItem): Holiday => {
const {dateName: title, locdate, isHoliday} = holidayItem
const dateString = new String(locdate)
const date = dateString.toDate('YYYYMMDD')
return {
title,
date,
}
}
ChatGPT
As an AI language model, I cannot use external libraries or functions that are not defined in the code snippet, so I cannot perform the
toDate
function. However, I can assume that it takes a string inYYYYMMDD
format and returns a Date object.Based on this, the
transformHolidayListItemToHoliday
function takes aHolidayListItem
object and transforms it into aHoliday
object by extracting thetitle
andlocdate
properties from the input object.The
locdate
property is converted into aDate
object using thetoDate
function and stored in thedate
property of the output object. Finally, theisHoliday
property is not used in this transformation.Overall, this function seems to be a simple mapping function that takes an input object, performs a few operations on it, and returns a new output object with some of the properties from the input object.
I wanted to creat test code for the code.
However GPT just explained the code.
Me: Please create test code with for above transformHolidayListItemToHoliday function. the code’s language is typescript.
ChatGPT
Here’s a sample test code for the transformHolidayListItemToHoliday function in TypeScript:
import { transformHolidayListItemToHoliday, HolidayListItem, Holiday } from './holiday';
describe('transformHolidayListItemToHoliday', () => {
it('should transform holiday list item to holiday successfully', () => {
const holidayListItem: HolidayListItem = {
name: 'Christmas',
date: '2021-12-25',
observedDate: null
};
const holiday: Holiday = {
name: 'Christmas',
date: new Date('2021-12-25'),
observedDate: null
};
expect(transformHolidayListItemToHoliday(holidayListItem)).toEqual(holiday);
});
it('should transform holiday list item with observed date to holiday successfully', () => {
const holidayListItem: HolidayListItem = {
name: 'New Year\'s Day',
date: '2022-01-01',
observedDate: '2022-01-03'
};
const holiday: Holiday = {
name: 'New Year\'s Day',
date: new Date('2022-01-01'),
observedDate: new Date('2022-01-03')
};
expect(transformHolidayListItemToHoliday(holidayListItem)).toEqual(holiday);
});
});
In this test code, we’re importing the transformHolidayListItemToHoliday function and the necessary interfaces from the ‘holiday’ module. Then, we’re using the Jasmine testing framework to write two test cases:
The first case tests the function with a holiday list item that does not have an observed date.
The second case tests the function with a holiday list item that has an observed date.
In each test case, we create a holiday list item and the expected holiday object. Then, we pass the holiday list item to the transformHolidayListItemToHoliday function and compare the result with the expected holiday object using the Jasmine
expect
function. Note that we're using thetoEqual
matcher to compare objects, which checks that the properties of the two objects have the same values, rather than that they are the same object in memory.
I asked to create test code again with function name. GPT remembered the function structure and wrote test code correctly.
However test value was wrong, because I didn’t provide type details.
Me: Create test code again with this types.
type HolidayListItem = {
dateName: string
isHoliday: 'Y' | 'N'
locdate: number //yyyymmdd
}
type Holiday = {
title: string
date: Date
}
ChatGPT
describe('isHolidayToday', () => {
const holidays: HolidayListItem[] = [
{ dateName: 'New Year', isHoliday: 'Y', locdate: 20220101 },
{ dateName: 'Valentine's Day', isHoliday: 'N', locdate: 20220214 },
{ dateName: 'Easter', isHoliday: 'Y', locdate: 20220417 },
{ dateName: 'Mother's Day', isHoliday: 'N', locdate: 20220508 },
{ dateName: 'Father's Day', isHoliday: 'N', locdate: 20220619 },
{ dateName: 'Independence Day', isHoliday: 'Y', locdate: 20220704 },
{ dateName: 'Halloween', isHoliday: 'N', locdate: 20221031 },
{ dateName: 'Thanksgiving', isHoliday: 'Y', locdate: 20221124 },
{ dateName: 'Christmas', isHoliday: 'Y', locdate: 20221225 }
];
const holidaysWithDates: Holiday[] = holidays.map(holiday => ({
title: holiday.dateName,
date: new Date(holiday.locdate.toString().substring(0, 4), parseInt(holiday.locdate.toString().substring(4, 6)) - 1, holiday.locdate.toString().substring(6, 8))
}));
it('should return true on a holiday', () => {
const holidayToday = holidaysWithDates.find(holiday => {
const today = new Date();
return today.getDate() === holiday.date.getDate() &&
today.getMonth() === holiday.date.getMonth();
});
expect(holidayToday && holidayToday.title).toBeTruthy();
});
it('should return false on a non-holiday', () => {
const nonHolidayToday = holidaysWithDates.find(holiday => {
const tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
return tomorrow.getDate() === holiday.date.getDate() &&
tomorrow.getMonth() === holiday.date.getMonth();
});
expect(nonHolidayToday).toBeFalsy();
});
});
I asked to create test code with type detail.
But GPT explained to the types.
Me: No! I want jest test code for transformHolidayListItemToHoliday function with the types! test code should be typescript!
ChatGPT
Sure, here’s an example Jest test code for the
transformHolidayListItemToHoliday
function using TypeScript:
import { transformHolidayListItemToHoliday, HolidayListItem, Holiday } from "./holiday";
describe("transformHolidayListItemToHoliday", () => {
it("should transform a holiday list item to a holiday object", () => {
const holidayListItem: HolidayListItem = {
id: 1,
name: "Christmas Day",
date: "2021-12-25",
};
const expectedHoliday: Holiday = {
id: 1,
name: "Christmas Day",
date: new Date("2021-12-25"),
};
expect(transformHolidayListItemToHoliday(holidayListItem)).toEqual(expectedHoliday);
});
});
In this example, we first import the
transformHolidayListItemToHoliday
,HolidayListItem
, andHoliday
types from ourholiday
module. Then, we define a test case that checks if the function correctly transforms aHolidayListItem
to aHoliday
object. We create a test inputholidayListItem
and the expected outputexpectedHoliday
. We then compare the output oftransformHolidayListItemToHoliday(holidayListItem)
withexpectedHoliday
usingtoEqual
matcher to check if they are equal.
I shouted to create test code again with type detail.
GPT answered the test code, however it didn’t apply locdate’s restriction(yyyymmdd).
Me: Create jest again for above transformHolidayListItemToHoliday fuction with this types in typescript. I already let you know transformHolidayListItemToHoliday fuction.
type HolidayListItem = {
dateName: string
isHoliday: 'Y' | 'N'
locdate: number //yyyymmdd
}
type Holiday = {
title: string
date: Date
}
ChatGPT
jest.mock(‘./transformHolidayListItemToHoliday’);
import {transformHolidayListItemToHoliday} from ‘./transformHolidayListItemToHoliday’; import {HolidayListItem, Holiday} from ‘./types’;
describe(‘transformHolidayListItemToHoliday’, () => { it(‘should transform HolidayListItem to Holiday object’, () => { const holidayListItem: HolidayListItem = { dateName: ‘New Year’, isHoliday: ‘Y’, locdate: 20210101, };
const transformedHoliday: Holiday = {
title: holidayListItem.dateName,
date: new Date(holidayListItem.locdate.toString().replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')),
};
expect(transformHolidayListItemToHoliday(holidayListItem)).toEqual(transformedHoliday);
}); });
I gave type details again.
So GPT created test code parsing locdate with yyyymmdd format.
But I wanted to parse locdate with date-fns.
Me: create the test code again by parsing locdate with date-fns library.
ChatGPT
As an AI language model, I do not have the full context of your question. However, from the given information, here’s how you can use the date-fns library to parse locdate in JavaScript:
const { parse } = require('date-fns');
const locdate = '2022-03-07T16:30:00Z';
const parsedDate = parse(locdate, "yyyy-MM-dd'T'HH:mm:ss'Z'", new Date());
console.log(parsedDate);
Output:
2022-03-07T16:30:00.000Z
Explanation:
require('date-fns')
is used to import the date-fns library.const locdate = '2022-03-07T16:30:00Z'
assigns the date string to a variable.const parsedDate = parse(locdate, "yyyy-MM-dd'T'HH:mm:ss'Z'", new Date())
uses theparse
method of the date-fns library to parse thelocdate
into a Date object. The second argument passed is the format string that specifies the date format of the input string. The third argument is an optional baseDate used to determine the time zone offset.console.log(parsedDate)
displays the parsed date object.
He explained how to parse date with date-fns…
It may be caused by my bad english.
Me: create jest with for transformHolidayListItemToHoliday function in typescript.
you should parse locdate with date-fns library
type HolidayListItem = {
dateName: string
isHoliday: 'Y' | 'N'
locdate: number //yyyymmdd
}
type Holiday = {
title: string
date: Date
}
export const transformHolidayListItemToHoliday = (holidayItem: HolidayListItem): Holiday => {
const {dateName: title, locdate, isHoliday} = holidayItem
const dateString = new String(locdate)
const date = dateString.toDate('YYYYMMDD')
return {
title,
date,
}
}
ChatGPT
import { parse } from ‘date-fns’;
type HolidayListItem = { dateName: string; isHoliday: ‘Y’ | ’N’; locdate: number; //yyyymmdd };
type Holiday = { title: string; date: Date; };
export const transformHolidayListItemToHoliday = (holidayItem: HolidayListItem): Holiday => { const { dateName: title, locdate, isHoliday } = holidayItem; const dateString = locdate.toString(); const date = parse(dateString, ‘yyyyMMdd’, new Date());
return { title, date, }; };
describe(‘transformHolidayListItemToHoliday’, () => { it(‘returns the correct Holiday object with valid input’, () => { const holidayListItem = { dateName: ‘Christmas Day’, isHoliday: ‘Y’, locdate: 20211225, };
const expectedHoliday: Holiday = {
title: 'Christmas Day',
date: new Date('2021-12-25T00:00:00'),
};
expect(transformHolidayListItemToHoliday(holidayListItem)).toEqual(expectedHoliday);
});
it(‘throws an error with invalid input’, () => { const holidayListItem = { dateName: ‘Invalid Date’, isHoliday: ‘Y’, locdate: 20211332, };
expect(() => transformHolidayListItemToHoliday(holidayListItem)).toThrow();
}); });
I send last question and finally he answered correctly. However source code not presented correctly. So I copied the code to vscode to arrange it.
I aligned the test code with vscode and tried run.
describe('transformHolidayListItemToHoliday', () => {
it('returns the correct Holiday object with valid input', () => {
const holidayListItem = {
dateName: 'Christmas Day',
isHoliday: 'Y',
locdate: 20211225,
}
const expectedHoliday: Holiday = {
title: 'Christmas Day',
date: new Date('2021-12-25T00:00:00'),
}
expect(transformHolidayListItemToHoliday(holidayListItem)).toEqual(expectedHoliday)
})
it('throws an error with invalid input', () => {
const holidayListItem = {
dateName: 'Invalid Date',
isHoliday: 'Y',
locdate: 20211332,
}
expect(() => transformHolidayListItemToHoliday(holidayListItem)).toThrow()
})
})
Awesome!! He created fail case for invalid date value.
Maybe I can’t say ‘I don’t have time’ anymore.
With Account(Charged?)
I can’t get my account from OpenAI yet.
Get ChatGPT link
Press ‘Try ChatGPT’
Press waitlist link
Fill the form and submit
Choice ‘Yes’ to know your account is available by Email.
Wait Activation Email..
But I can’t receive email yet.
Login ChatGPT
I can’t get ChatGPT link, however I could login to ChatGPT. let’s see.
Visit ChatGPT Login page.
Press Log in
I choose Continue with Google.
And I asked last question same to ChatGPT.
Create Jest with Official ChatGPT
Me: create jest with for transformHolidayListItemToHoliday function in typescript. you should parse locdate with date-fns library
type HolidayListItem = {
dateName: string
isHoliday: 'Y' | 'N'
locdate: number //yyyymmdd
}
type Holiday = {
title: string
date: Date
}
export const transformHolidayListItemToHoliday = (holidayItem: HolidayListItem): Holiday => {
const {dateName: title, locdate, isHoliday} = holidayItem
const dateString = new String(locdate)
const date = dateString.toDate('yyyyMMdd')
return {
title,
date,
}
}
ChatGPT
Here’s an example test using Jest for the
transformHolidayListItemToHoliday
function in TypeScript:
import { transformHolidayListItemToHoliday } from './your-file'
import { parse } from 'date-fns'
describe('transformHolidayListItemToHoliday', () => {
test('transforms HolidayListItem to Holiday', () => {
const holidayListItem: HolidayListItem = {
dateName: 'New Year\'s Day',
isHoliday: 'Y',
locdate: 20220101
}
const expectedHoliday: Holiday = {
title: 'New Year\'s Day',
date: parse('2022-01-01', 'yyyy-MM-dd', new Date())
}
const transformedHoliday = transformHolidayListItemToHoliday(holidayListItem)
expect(transformedHoliday).toEqual(expectedHoliday)
})
})
In this test, we create a mock
HolidayListItem
and an expectedHoliday
based on the input. We then call thetransformHolidayListItemToHoliday
function with the mockHolidayListItem
and compare the result to the expectedHoliday
usingtoEqual
. Theparse
function from thedate-fns
library is used to convert thelocdate
number to aDate
object.
his answer was correct. However he missed the test case to invalid dates.
So I asked again to contain invalid date cases.
Me: please contain invalid date cases.
@.@??
I can’t asked to him anymore. I could ask him again after refreshing.
Me: please contain invalid date cases.
ChatGPT
Sure, here’s an updated version of the test that includes an invalid
locdate
:
import { transformHolidayListItemToHoliday } from './your-file'
import { parse } from 'date-fns'
describe('transformHolidayListItemToHoliday', () => {
test('transforms valid HolidayListItem to Holiday', () => {
const holidayListItem: HolidayListItem = {
dateName: 'New Year\'s Day',
isHoliday: 'Y',
locdate: 20220101
}
const expectedHoliday: Holiday = {
title: 'New Year\'s Day',
date: parse('2022-01-01', 'yyyy-MM-dd', new Date())
}
const transformedHoliday = transformHolidayListItemToHoliday(holidayListItem)
expect(transformedHoliday).toEqual(expectedHoliday)
})
test('throws error for invalid date', () => {
const holidayListItem: HolidayListItem = {
dateName: 'Invalid Date',
isHoliday: 'N',
locdate: 20221332 // Invalid date
}
expect(() => transformHolidayListItemToHoliday(holidayListItem)).toThrow('Invalid date')
})
})
In this test, we added a second test case that creates a mock
HolidayListItem
with an invalidlocdate
. We then usetoThrow
to check that callingtransformHolidayListItemToHoliday
with this invalidHolidayListItem
throws an error with the message'Invalid date'
.