Created
September 2, 2018 18:02
-
-
Save joerter/b14c22ccb1d1958682029e514859cef0 to your computer and use it in GitHub Desktop.
An Angular component class test using a stub function to create typed dependencies
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; | |
// loggingServiceStub is now a real LogginService | |
const loggingServiceStub = stub<LoggingService>(); | |
loggingServiceStub.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