Tests of QCD factorisation in the diffractive production of dijets in deep inelastic scattering and photoproduction at HERA