There is a table in the template, and the status of project will be displayed.
name
status
date
name1
Passed
1990-04-01 11:00
name2
Stalled
1980-04-01 11:00
and the status value is connected and taken from the backend, through the Dto.
And IF we need to display the value always with first letter in capital, but actually in the backend, the data is stored inside JSON file, also like following
Then in the test file, we need to mock the status data, with the correct type.
const ENUM_STATUS_MOCK = {
[TableDto.StateEnum.PASSED]: 'Passed',
[TableDto.StateEnum.PENDING]: 'Pending',
[TableDto.StateEnum.STALLED]: 'Stalled',
}
===> Notice here we use Required and Pick,
const DATA_MOCK: Array<Required<Pick<TableDto, 'name' | 'status'|'date'>> & TableDto> =[
{
name: 'name1',
date: new Date('1990-04-01 01:00 AM'),
status: TableDto.StateEnum.PASSED,
id: 'id1',
},
{
name: 'name2',
date: new Date('1980-04-01 01:00 AM'),
status: TableDto.StateEnum.STALLED,
id: 'id2',
}
]
@Pipe({name: 'enumPipe'}) <=== here the string taken from the pipe
class EnumPipeMock implements PipeTransform {
public transform(input: TableDto.StateEnum): Observable<string>{
return of (ENUM_STATUS_MOCK[input])
}
}
describe(... , ( ) => {
it('should .....' ( ) = > {
fixture.detectChanges();
fixture.whenStable().then( ()=>{
const tableRowElements = table.nativeElement.querySelectorAll('tbody tr') as HTMLTableRowElement[];
tableRowElements.forEach((row, rowIndex) => {
const {name, status} = DATA_MOCK(rowIndex);
const tdElements = row.querySelectorAll('td');
expect(tdElements[0].innerHTML).toBe(name);
expect(tdElements[1].innerHTML).toBe(ENUM_STATUS_MOCK[status]); <====
expect(tdElements[2].innerHTML).toBe(moment(date).format('YYYY-MM-DD HH:mm'))
}
})
})
});
👉 Notice here we use Required and Pick, first we Pick'name' | 'status'|'date' from the TableDto, and then use Required to make this required, then add& the rest of TableDto
Background
There is a table in the template, and the
status
of project will be displayed.and the status value is connected and taken from the backend, through the Dto.
And
IF
we need to display the value always with first letter in capital, but actually in the backend, the data is stored inside JSON file, also like followingTherefore, if we fetch the data directly from the backend, the 'PASSED' instead of 'Passed' will be displayed in the table.
Therefore, we need a
PIPE
for the translating.So we have a
EnumPipeModule
here.table.module.ts
table.component.ts
table.component.html
table.component.ts
if the data like
status
is taken from tableDto.ts filetableDto.ts
table.component.spec.ts
Then in the test file, we need to mock the status data, with the correct type.
👉 Notice here we use
Required
andPick
, first wePick
'name' | 'status'|'date'
from theTableDto
, and then useRequired
to make this required, thenadd
&
the rest ofTableDto