Skip to content

Instantly share code, notes, and snippets.

@jschwarty
Created July 28, 2016 16:51
Show Gist options
  • Save jschwarty/c6bdc4ced33a4686fb9bcf234343d2d0 to your computer and use it in GitHub Desktop.
Save jschwarty/c6bdc4ced33a4686fb9bcf234343d2d0 to your computer and use it in GitHub Desktop.
Issues with testing parameter guard logic when using TypeScript
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);
});
});
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;
}
}
}
<!--
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