2

Hi I am working on angular2. I am writing unit test case for delete operation. In real time I am making API call to delete user. To unit test i have created json objecr array and I am making required operations. Below is my code for delete operation.

 it('should', async(() => {
        spyOn(component, 'deleteUser');
        let button = fixture.debugElement.nativeElement.querySelector('deleteUser');
        button.click();
        fixture.whenStable().then(() => {
            expect(component.deleteUser).toHaveBeenCalled();
        })
        alert(1);
    }));

Below is my service.

  deleteUserEndpoint(userid: string) {
        var deleteUserUserOnboard = { result: true };
        return Observable.of(deleteUserUserOnboard);
    }

Below is my html code.

 <a class="btn btn-link btn-xs" href="javascript:;" id="deleteUser" (click)="deleteUser(row)"><i class="fa fa-trash-o" aria-hidden="true"></i> {{'users.management.Delete' | translate}}</a>

I have below error.

Failed: Cannot read property 'click' of null 

I am newbie to unit testing. Can someone tell me what would be the expected behavior? Also may I know am I doing something wrong here? Any help would be appreciated. Thank you.

1 Answer 1

1

Its not able to get button object in button.click() , as per your error text.
I think providing deleteUser button's ID (#deleteUser instead of deleteUser) would help you get it.

fixture.debugElement.nativeElement.querySelector('#deleteUser')
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. After adding # in the beginning error fixed. But i am started to get Expected spy on deleteUser to be 'true'. this error. May I know what would be I am missing here?
not getting it. Could you please rephrase? what's there in deleteUser function?
After expect i have added expect(component.deleteUser).toBe('true');. I removed it now. It is working fine now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.