Last active
August 12, 2018 19:03
-
-
Save joerter/e3b093dd8c4e0d519c462f764bc1c830 to your computer and use it in GitHub Desktop.
An example of how to write a component class test for an Angular component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on example from: https://angular.io/guide/component-interaction#parent-listens-for-child-event | |
@Component({ | |
selector: 'app-voter' | |
}) | |
export class VoterComponent { | |
@Output() voted = new EventEmitter<boolean>(); | |
didVote = false; | |
constructor(private loggingService: LoggingService){} | |
vote(agreed: boolean) { | |
this.voted.emit(agreed); | |
this.didVote = true; | |
this.loggingService.logVote(agreed); | |
} | |
} | |
describe('VoterComponent', () => { | |
let component: VoterComponent; | |
let emittedValue: boolean; | |
let loggedVote: boolean; | |
let loggingServiceStub = <any>{ | |
logVote: (vote: boolean) => { loggedVote = vote; } | |
}; | |
beforeEach(() => { | |
emittedValue = undefined; | |
loggedVote = undefined; | |
// inject the service stub into the constructor | |
component = new VoterComponent(loggingServiceStub); | |
// set the output property equal to an object | |
// with a function that sets the passed in | |
// value to something we can make assertions against. | |
component.voted = <any>{ | |
emit: (didVote: boolean) => { emittedValue = didVote; } | |
}; | |
}); | |
describe('vote', () => { | |
// simple case of asserting against a property | |
// of the component | |
it('should set didVote to true', () => { | |
component.vote(false); | |
expect(component.didVote).toBe(true); | |
}); | |
// asserting against an output property | |
it('should emit the value', () => { | |
const expectedValue = true; | |
component.vote(expectedValue); | |
expect(emittedValue).toBe(expectedValue); | |
}); | |
// asserting against the correct | |
// usage of a service dependency | |
it('should log the value', () => { | |
const expectedValue = false; | |
component.vote(expectedValue); | |
expect(loggedVote).toBe(expectedValue); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment