Created
July 28, 2016 16:51
-
-
Save jschwarty/c6bdc4ced33a4686fb9bcf234343d2d0 to your computer and use it in GitHub Desktop.
Issues with testing parameter guard logic when using TypeScript
This file contains hidden or 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
import { describe, it, expect, beforeEach } from '@angular/core/testing'; | |
import { InvalidPipeArgumentException } from '@angular/common/src/pipes/invalid_pipe_argument_exception'; | |
import { ConversionPipe } from './conversion.pipe'; | |
describe('ConversionPipe', () => { | |
let pipe: ConversionPipe; | |
beforeEach(() => { | |
pipe = new ConversionPipe(); | |
}); | |
it('errors on bad argument'), () => { | |
expect(() => pipe.transform(10)) // <-- TypeScript compile error here :( | |
.toThrowError(InvalidPipeArgumentException); | |
}); | |
}); |
This file contains hidden or 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
import { Pipe, PipeTransform } from '@angular/core'; | |
import { isString } from '@angular/core/src/facade/lang'; | |
import { InvalidPipeArgumentException } from '@angular/common/src/pipes/invalid_pipe_argument_exception'; | |
@Pipe({ | |
name: 'conversion' | |
}) | |
export class ConversionPipe implements PipeTransform { | |
public transform(value: string): string { | |
if (!isString(value)) { | |
throw new InvalidPipeArgumentException(ConversionPipe, value); | |
} | |
if (!value) { | |
return ''; | |
} else { | |
let newValue = value; // imagine some fantastic conversion things done to the value here... | |
return newValue; | |
} | |
} | |
} |
This file contains hidden or 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
<!-- | |
TypeScript is not going to help us here at dev time, so we need the guard in our pipe | |
to be able to give a runtime error. Thus it would be nice to be able to have a test | |
that confirms the pipe correctly throws that runtime error for us. | |
--> | |
<div> | |
{{ 1986 | conversion }} | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment