#test unit issue
48 messages · Page 1 of 1 (latest)
g!badeyes @toxic swan
@toxic swan Please do not post pictures of code (especially photos of a physical screen) as they are difficult to read and difficult to correct (as you cannot copy code from a screenshot to modify it).
And it will be difficult because of the setTimeout. Which is almost always not the best thing to do in Angular.
Sorry! This is not a code that I wrote
g!codeblock @toxic swan and show your code.
@toxic swan, you can use the following snippet to have your code formatted and colored by Discord. Replace ts with the language you need (i.e. html, js, css, etc)
```ts
// your code goes here
```
Might be able to use: https://angular.io/guide/testing-components-scenarios#async-test-with-fakeasync
I should cover the if statement inside
ngOnInit(): void {
const id = this.router.url.split('/')[3];
setTimeout(() => {
this.costPriceService.getCardById(id).subscribe((res: any) => {
if (res) {
this.dataSource = res.priceCorridors;
if (this.data) {
this.summary.customDutyCost = this.data.customDutyCost;
this.summary.incotermsCost = this.data.incotermsCost;
this.summary.incotermsPrice = this.data.incotermsPrice;
}
this.calculateTotalActivitiesFields(this.dataSource);
this.calculateTotalCapitalsFields(this.dataSource);
this.calculateContingencyCost();
this.calculateTotalAmountFields();
}
}, err => {
console.log(err);
});
}, 500);
}
I've never wrote a spec ts before. They asked to me to cover this if statement inside that
Someone can help?
I mean, that code needs to be refactored... don't wrap a subscribe inside a settimeout...
don't use 
The point is: this is not my code, they asked for a coverage for the if statement inside
I must do it, in a way or in another way
Doesn't matter
The important thing is that in sonarcube appears that I covered the if statement too...I'm not capable to do it, I think it's very difficult, I've never wrote testing unit before
Part of testing is to write code that can be unit tested
Yes, I'm totally agree with you, but now I'm sure that I can not refrabric the code
Is there a way to make a reference of that if from the spec?
I literally don't know how to refer to that if from the spec, I know that the code isn't wrote well, but I cannot change anything of that page, unfortunately
First thing is to add types to your implementation instead of using 
Rob already answered that/ Read https://angular.io/guide/testing-components-scenarios#async-test-with-fakeasync. You'll need to use fakeAsync and tick() to travel in the future.
interface Summary {
customDutyCost: number;
incotermsCost: number;
incotermsPrice: number;
}
interface ViewModel {
dataSource?: PriceCorridors;
summary?: Summary;
}
@Component({
template: `
<pre *ngIf="vm$ | async as vm; else loading">
For Debugging: {{ vm | json }}
</pre>
<ng-template #loading>Loading...</ng-template>
`,
})
export class TheComponent {
public readonly vm$: Observable<ViewModel>;
constructor(
private readonly costPriceService: CostPriceService,
private readonly route: ActivatedRoute,
) {
this.vm$ = this.route.paramMap.pipe(
map((params: ParamMap): string => {
const maybeId: string | null = params.get('id');
if (!maybeId) {
throw new Error('Invalid URL path parameter ID');
}
return maybeId;
}),
switchMap((id: string): Observable<PriceCorridorsResponse | null> => this.costPriceService.getCardById(id)),
map((res: PriceCorridorsResponse | null): ViewModel => {
const ret: ViewModel = {};
if (res) {
ret.dataSource = res.priceCorridors;
if (this.data) {
this.summary.customDutyCost = this.data.customDutyCost;
this.summary.incotermsCost = this.data.incotermsCost;
this.summary.incotermsPrice = this.data.incotermsPrice;
}
this.calculateTotalActivitiesFields(ret.dataSource);
this.calculateTotalCapitalsFields(ret.dataSource);
this.calculateContingencyCost();
this.calculateTotalAmountFields();
}
}),
);
}
}
What is this? Keep in mind that what I send to you is only the Ng oninit, the code is much longer
Rob that's too difficult for me...I'm still a junior, unfortunately I do not understand everything you wrote there, but I'm sure that's a better way to code...now I have to remain with the code I sent to you, I cannot change anything of the code itself. I'm able only to write the spec.ts, do you know if it's possibile anyway to write something to cover that if? Even if it's not useful, I must obtain more points on sonarcube (Jenkins test)
g!toh @toxic swan Then you probably should put this aside and build the Tour of Heroes apps from the Angular Tutorial so you know what Angular can do and how it does it. There is also a section of the tutorial about testing, but you probably need to build the Tour of Heroes apps first in order to complete that.
@toxic swan The place we recommend starting your Angular journey is with the Tour of Heroes tutorial, located here https://angular.io/tutorial.
I cannot put this aside, I know how to code in angular, I'm not senior 4 sure, but I know the necessary things for working, that's not my app, this is a third part app that I have to support, and in order to do that I must add inside the spec this reference. This is work, not free time things
You seem to work in a disfunctional company. Making juniors test the code written by others to gain points on Sonarcube is really not a decent way of developing software. Run away if you can.
I'm totally agree with you, it's only for the moment. In a few days I should start develop new features or doing some defect...before then I must rise up the sonarcube overall testing score
That's why I come here, to be helped, not to be criticised😅
Have you read the link about fakeAsync that we sent twice?
Yes, twice, and I did not understand anything...thats very difficult to understand, I've NEVER tested anything
I'm working on this code since yesterday
I'm panicking
Then forget about that task for now, and
- Learn about testing
- Start practicing on very simple basic functions
- Start practicing on very simple components
- Continue learning about jasmine spies/mocks
- Start practicing on a bit more complex components, involving mocking dependencies
- Start practicing on a very simple example involving a setTimeout, using fakeAcync and tick
- Start trying to actually test the code you need to test, but only if you understand what it's supposed to do, and not just what it does. Otherwise you'll just test that the code implements a bug.
In all of this, you should have mentoring from your company.
Ok then, let's forget about the code I wrote before
This is a basic code
Can someone help me to understand?
if (data) {
data.activities.forEach(activity => {
if (activity.isVisible !== false) {
activity.additionalLines.forEach(line => {
if (line.isVisible !== false) {
this.summary.totalActivitiesCost += line.totalCost ? line.totalCost : 0;
this.summary.totalActivitiesCost = +this.summary.totalActivitiesCost.toFixed(2);
}
});
this.summary.totalActivitiesChosenPrice += activity.chosenPrice ? activity.chosenPrice : 0;
// this.summary.totalActivitiesChosenPrice += activity[activity.selectedRadioButton] ? activity[activity.selectedRadioButton] : 0;
this.summary.totalActivitiesChosenPrice = +this.summary.totalActivitiesChosenPrice.toFixed(2);
if (this.summary.totalActivitiesChosenPrice > 0) {
this.summary.totalActivitiesCmChosenPrice =
((this.summary.totalActivitiesChosenPrice - this.summary.totalActivitiesCost) / this.summary.totalActivitiesChosenPrice) * 100;
this.summary.totalActivitiesCmChosenPrice = +this.summary.totalActivitiesCmChosenPrice.toFixed(2);
}
this.summary.totalActivitiesDiscountedPrice += activity.discountedPrice ? activity.discountedPrice : 0;
this.summary.totalActivitiesDiscountedPrice = +this.summary.totalActivitiesDiscountedPrice.toFixed(2);
if (this.summary.totalActivitiesDiscountedPrice > 0) {
this.summary.totalActivitiesCmDiscountedPrice =
((this.summary.totalActivitiesDiscountedPrice - this.summary.totalActivitiesCost) / this.summary.totalActivitiesDiscountedPrice) * 100;
this.summary.totalActivitiesCmDiscountedPrice = +this.summary.totalActivitiesCmDiscountedPrice.toFixed(2);
}
}
});
this.calculateTotalAmountFields();
}
This is a simple one
I only need to be helped so I can move on alone
You're not approaching this the correct way. A test is not something intended to artificially increase code coverage in Sonarcube. A test is supposed to check that the code does what it's supposed to do. If you don't know what the code is supposed to do, you can't test. Let me explain with actual simple code:
/**
* returns the sum of the two numbers
*/
function sum(n1: number, n2: number) {
return 10;
}
What this code is supposed to do is in the documentation of the method. What the code does is in between the curly braces. If you ignore the comments explaining what the code is supposed to do and write a test to increase coverage, your test will be
it('should do anything', () => {
expect(sum(2, 4)).toBe(10);
}
This test will pass, it will increase coverage, but it's crap: it doesn't actually test that the code does what it's supposed to do.