@@ -1933,4 +1933,77 @@ describe('yargs-parser', function () {
19331933 parsed . f . should . deep . equal ( [ ] )
19341934 parsed . files . should . deep . equal ( [ ] )
19351935 } )
1936+
1937+ describe ( 'coerce' , function ( ) {
1938+ it ( 'applies coercion function to simple arguments' , function ( ) {
1939+ var parsed = parser ( [ '--foo' , '99' ] , {
1940+ coerce : {
1941+ foo : function ( arg , cb ) {
1942+ return cb ( null , arg * - 1 )
1943+ }
1944+ }
1945+ } )
1946+ parsed . foo . should . equal ( - 99 )
1947+ } )
1948+
1949+ it ( 'applies coercion function to aliases' , function ( ) {
1950+ var parsed = parser ( [ '--foo' , '99' ] , {
1951+ coerce : {
1952+ f : function ( arg , cb ) {
1953+ return cb ( null , arg * - 1 )
1954+ }
1955+ } ,
1956+ alias : {
1957+ f : [ 'foo' ]
1958+ }
1959+ } )
1960+ parsed . foo . should . equal ( - 99 )
1961+ parsed . f . should . equal ( - 99 )
1962+ } )
1963+
1964+ it ( 'applies coercion function to an array' , function ( ) {
1965+ var parsed = parser ( [ '--foo' , '99' , '-f' , '33' ] , {
1966+ coerce : {
1967+ f : function ( arg , cb ) {
1968+ return cb ( null , arg * - 1 )
1969+ }
1970+ } ,
1971+ array : [ 'foo' ] ,
1972+ alias : {
1973+ f : [ 'foo' ]
1974+ }
1975+ } )
1976+ parsed . f . should . deep . equal ( [ - 99 , - 33 ] )
1977+ parsed . foo . should . deep . equal ( [ - 99 , - 33 ] )
1978+ } )
1979+
1980+ // see: https://github.com/yargs/yargs/issues/550
1981+ it ( 'coercion function can be used to parse large #s' , function ( ) {
1982+ var fancyNumberParser = function ( arg , cb ) {
1983+ if ( arg . length > 10 ) return cb ( null , arg )
1984+ else return cb ( null , parseInt ( arg ) )
1985+ }
1986+ var parsed = parser ( [ '--foo' , '88888889999990000998989898989898' , '--bar' , '998' ] , {
1987+ coerce : {
1988+ foo : fancyNumberParser ,
1989+ bar : fancyNumberParser
1990+ }
1991+ } )
1992+ ; ( typeof parsed . foo ) . should . equal ( 'string' )
1993+ parsed . foo . should . equal ( '88888889999990000998989898989898' )
1994+ ; ( typeof parsed . bar ) . should . equal ( 'number' )
1995+ parsed . bar . should . equal ( 998 )
1996+ } )
1997+
1998+ it ( 'populates argv.error, if an error is returned' , function ( ) {
1999+ var parsed = parser . detailed ( [ '--foo' , '99' ] , {
2000+ coerce : {
2001+ foo : function ( arg , cb ) {
2002+ return cb ( Error ( 'banana' ) , arg * - 1 )
2003+ }
2004+ }
2005+ } )
2006+ parsed . error . message . should . equal ( 'banana' )
2007+ } )
2008+ } )
19362009} )
0 commit comments