There are no rules, only guidelines.
Challnge rating calculation is hardly an exact science. There are simply too many variables. An objective calculation of challenge rating could very easily comprise a multi-volume collection of sourcebooks if every variable is considered. Instead, the Dungeon Master's Guide gives some rough guidelines to follow, but largely expects you to do most of the work yourself - especially when it comes to factoring in spellcasting. On this point, the DMG says:
The impact that the Innate Spellcasting and Spellcasting special traits have on a monster’s challenge rating depends on the spells that the monster can cast. Spells that deal more damage than the monster’s normal attack routine and spells that increase the monster’s AC or hit points need to be accounted for when determining the monster’s final challenge rating.
So spellcasting, in particular, the spells the NPC can cast, definitely need to be factored in to a CR calculation. This answer has some helpful guidelines for factoring spellcasting into your offensive CR calculations. Following the formula there, but adapting it for defensive CR, is left as an exercise to the reader, but should be easy enough.