0

I am trying to write a unit test for a matSortChange function. This emits a Sort Event that I thought was just an object with an active property and direction property. My test currently looks like:

it('sort unit test', () => {
 const fakeSortEvent = {active: 'fakeActive', direction: 'asc'};
 component.saveSort(fakeSortEvent);

})

The TS error I am getting is

Types of property 'direction' are incompatible.
Type 'string' is not assignable to type 'SortDirection'

When looking up what SortDirection looks like angular material docs, it seems like my fakeSortEvent object should work. How can I create a mock Sort Event?

Brian Stanley
  • 2,078
  • 5
  • 24
  • 43
  • As error says, direction could not be type of string, it should be type of StringDirection that could be 'asc', 'desc' or ' '. More about that you can see it [here](https://material.angular.io/components/sort/api#SortDirection) – trisek Feb 20 '20 at 20:46
  • So SortDirection just being a string of either 'asc' | 'desc' | ' ', shouldn't the fakeSortEvent I created work? giving direction 'asc'? – Brian Stanley Feb 20 '20 at 20:54
  • Yes you are right, this should work. Can you try create fakeSortEvent like this: ```const fakeSortEvent: Sort = {active: 'fakeActive', direction: 'asc'}```. I don't know if this will work, but you can try it. – trisek Feb 20 '20 at 21:22
  • OMG! that worked...... Thank you @diabolique. Going to call it for the day after that. – Brian Stanley Feb 20 '20 at 21:38

1 Answers1

0

Thank @diabolique for the answer in the commments. Adding type Sort to fakeSortEvent has it working. Code:

it('sort unit test', () => {
 const fakeSortEvent: Sort = {active: 'fakeActive', direction: 'asc'};
 component.saveSort(fakeSortEvent);
})
Brian Stanley
  • 2,078
  • 5
  • 24
  • 43