to-have-been-warned.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. function noop () {}
  2. if (typeof console === 'undefined') {
  3. window.console = {
  4. warn: noop,
  5. error: noop
  6. }
  7. }
  8. // avoid info messages during test
  9. console.info = noop
  10. let asserted
  11. function hasWarned (msg) {
  12. var count = console.error.calls.count()
  13. var args
  14. while (count--) {
  15. args = console.error.calls.argsFor(count)
  16. if (args.some(containsMsg)) {
  17. return true
  18. }
  19. }
  20. function containsMsg (arg) {
  21. return arg.toString().indexOf(msg) > -1
  22. }
  23. }
  24. // define custom matcher for warnings
  25. beforeEach(() => {
  26. asserted = []
  27. spyOn(console, 'error')
  28. jasmine.addMatchers({
  29. toHaveBeenWarned: () => {
  30. return {
  31. compare: msg => {
  32. asserted = asserted.concat(msg)
  33. var warned = Array.isArray(msg)
  34. ? msg.some(hasWarned)
  35. : hasWarned(msg)
  36. return {
  37. pass: warned,
  38. message: warned
  39. ? 'Expected message "' + msg + '" not to have been warned'
  40. : 'Expected message "' + msg + '" to have been warned'
  41. }
  42. }
  43. }
  44. }
  45. })
  46. })
  47. afterEach(done => {
  48. const warned = msg => asserted.some(assertedMsg => msg.toString().indexOf(assertedMsg) > -1)
  49. let count = console.error.calls.count()
  50. let args
  51. while (count--) {
  52. args = console.error.calls.argsFor(count)
  53. if (!warned(args[0])) {
  54. done.fail(`Unexpected console.error message: ${args[0]}`)
  55. return
  56. }
  57. }
  58. done()
  59. })