Search code examples
vbscriptasp-classic

Type mismatch error in VBscript when calling a custom subroutine


I have this subroutine:

Sub AssertTrue(condition, success, error)
    If condition Then
        %><div style='color:black'><%=success%></div><%
    Else
        %><div style='color:red'><%=error%></div><%
    End If
End Sub

And when I call it like so:

AssertTrue IsNullOrWhiteSpace(Empty), "Empty is blank.", "Empty is not blank."

using this function:

' Determines if a string is null, blank, or filled with whitespace.
' If an array of strings is passed in, the first string is checked.
Function IsNullOrWhiteSpace(str)
    If IsArray(str) Then
        If str.Length > 0 Then str = str(0) Else str = Empty
    End If
    IsNullOrWhiteSpace = IsEmpty(str) Or (Trim(str) = "")
End Function

Then I get a type mismatch error on the AssertTrue call. But VBscriptis a weakly typed language and I don't see where types are getting mixed up - IsNullOrWhiteSpace does return a boolean! Why am I getting this error and how can I fix it?

And yes, I am attempting to create unit tests in VBscript. If there's a better way to do so, please let me know... :)


Solution

  • The Type Mismatch error is exactly what it says, you are referencing a type incorrectly or not as expected.

    The problem is in the IsNullOrWhiteSpace() function call, on this line;

    If str.Length > 0 Then str = str(0) Else str = Empty
    

    caused by referencing a string as an object reference. Strings do not contain properties like object types do so the str.Length in the code is causing a Type Mismatch error.

    To check the length of a string you should use;

    Len(str)
    

    In this case though you appear to be checking an Array so you should be using;

    UBound(str)