简体   繁体   中英

How to reflect Angular component.ts changes in associated spec.ts file

I have just started a new job, and my first project is working on an Angular web app. This is my first experience with Angular, so I am still learning the foundations.

What I'm having some difficulty with is adjusting existing component.spec.ts files to work with some changes I make in the associated component.ts files.

I'm fairly certain that my changes work fine, but the resulting unit test pipelines fail because I believe the spec files need to be changed to reflect my new code. I have tried working through Angular's testing documentation, but it is not helping me make progress.

I can't really show my code specifically, as it's proprietary. Nor do I have the level of understanding in Angular to make it into a mock example. But perhaps I can abstract some components and you can give me whatever guidance you can.

If I edited an existing component.ts file to now have

@Input() user: User; in the export class area, as well as added a function:

ngOnInit() {
     this.client = this.allClients[0].client;
     this.setClient(this.client);
   }

How will my spec file need to change to accommodate the changes?

Right now, all 6 of the unit tests fail with the error message:

TypeError: Cannot read property '0' of undefined presumably because I'm accessing a property of 'user', and user previously wasn't needed at all.

I apologize in advance, as this is probably very difficult to be constructive without seeing the full code, but any guidance or resources are highly appreciated.

Welcome!

First, you need to mock the 'allClients' array and return whatever data you need.

allClients could look like this for example:

mockAllClients: [
    mockData: 0,
    client: 'John Smith'
]

Then, in the beforeEach() function, call the spyOn() function to return the mock data from wherever you get it (I'm assuming your getting it from a HTTP call or passing it into the component).

An example for this would be (assuming you're requesting the data from a server):

spyOn(someService, 'someEndpoint').and.returnValue(allClients[])

This will now run before each test, effectively taking care of the data required in ngOninit which runs before each test.

Once you've got that, you can test the setClient() method individually or simply mock the response using the spyOn() method above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM