In my Angular service, I have two properties of the same type. For testing purposes, I am pushing the same objects in reverse order to both properties. However, when I modify one object in one array, I notice that the same change reflects in the second array as well, even though I don't mention the second array in the code. Below is my service class:
class Myservice {
public meetings : Meeting [];
public participated : Meeting [];
constructor(){
this.meeting = [];
this.participated = [];
}
create(participants, id){
let meeting : Meeting = {
id : id,
participants : participants
}
this.meetings.push(meeting);
this.participated.unshift(meeting);
}
addParticipant(userId : number, meetingId : number){
this.meetings.forEach((meeting : Meeting) => {
if(meeting.id == meetingId) {
meeting.participants.push(userId)
}
})
}
}
Here is my Meeting Interface:
interface Meeting {
id : number;
participants : Array<number>;
}
This is how I test it:
describe('My service', () => {
let provider : Myservice;
beforeEach( () => {
provider = new Myservice();
});
it('should add a participant to the participants', () => {
provider.create([2], 1);
provider.create([2], 2);
provider.create([2], 3);
provider.create([2], 4);
provider.addParticipant(6, 3);
expect(provider.meetings[2].participants).toEqual([2,6])
//expect(provider.participated[1].participants).toEqual([2,6])
console.log('meeting par:', provider.meetings[2].participants)
console.log('Partic par:', provider.participated[1].participants)
})
The test passes as expected, but I noticed that the object in the participated array also changed. Any ideas why this might be happening? Versions of Karma/Jasmine used:
"@types/jasmine": "^3.3.13",
"@types/node": "^12.0.4",
"angular2-template-loader": "^0.6.2",
"core-js": "^3.1.3",
...
Edit: Even with the updated form of the create
function, the issue persists:
create(participants, id){
this.meetings.push({
id : id,
participants : participants
});
this.participated.unshift({
id : id,
participants : participants
});
}