0

new to Angular and testing.

In this method in the main code

private isReIndexActive(view: ViewShortDto): boolean {
    return view.dataFlowTaskName && this.isViewCompleted(view);
}

I created a test case in the

it('should check if Re-Run Index is not active', () => {
    const isActionEnabled = service.itemActions[4].isActive(SHORT_VIEWS[3]);

    expect(isActionEnabled).toBeFalse();
});

and the mock data is

{
    systemName: 'xxx-xxx-xxx',
    name: 'Demo',
    step: 6,
    indexStatus: 'Completed',
    dataFlowTaskName: null,
  }

when I run the unit test, the the output result is expected null to be false. however the return type in the main code is boolean. why is this error being shown?

Changed the code to tobeFalsy() however, the code review told it is not best practise.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    Does this answer your question? [Logical operators in JavaScript — how do you use them?](https://stackoverflow.com/questions/4535647/logical-operators-in-javascript-how-do-you-use-them) – VLAZ Jan 19 '23 at 15:54
  • `view.dataFlowTaskName && this.isViewCompleted(view);` will return `null` because `view.dataFlowTaskName` is `null` -> `null` is falsy -> the operator short-circuits and returns the first falsy value. Congratulations - you've found a bug in your application. Apparently it doesn't expect that the value could be `null` since the method is typed as returning `boolean`. Most likely you don't have `strictNullChecks` enabled in the TS compiler options which would have notified you about this. – VLAZ Jan 19 '23 at 15:55
  • @VLAZ will adding a constant before the `return` help fix this issue? such as ```const variable: boolean = view.dataFlowTaskName; return variable && this.isViewCompleted(view); ``` – Arvin Pradhan Jan 19 '23 at 16:03
  • There is not enough here to answer the question. Do not post code fragments. Post examples that fully describe and reproduce the issue. https://stackoverflow.com/help/how-to-ask –  Jan 19 '23 at 16:12
  • @E.Maggini I don't know what other information you need. The test expects `false` but `null && ` returns `null` which is not `false`, so the assertion fails. The entire answer is that `null && ` returns `null`. See the duplicate that goes into how logical operators work. – VLAZ Jan 19 '23 at 16:53
  • @ArvinPradhan no. If you need to return `false`, then change the method to return `false`. If you're OK with it returning `null` (a falsy value) then change your test to accept that. – VLAZ Jan 19 '23 at 16:54
  • @VLAZ you mean besides the fact that the method OP mentions is not referenced at all in the test case nor do they explain the relevance of the mock data to the test? The reason OP is getting null is likely because they have not provided a service to the test and hence null. But there's no way of knowing without a complete example. –  Jan 19 '23 at 16:58

0 Answers0