to-have-been-warned.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 createCompareFn (spy) {
  12. const hasWarned = msg => {
  13. var count = spy.calls.count()
  14. var args
  15. while (count--) {
  16. args = spy.calls.argsFor(count)
  17. if (args.some(containsMsg)) {
  18. return true
  19. }
  20. }
  21. function containsMsg (arg) {
  22. return arg.toString().indexOf(msg) > -1
  23. }
  24. }
  25. return {
  26. compare: msg => {
  27. asserted = asserted.concat(msg)
  28. var warned = Array.isArray(msg)
  29. ? msg.some(hasWarned)
  30. : hasWarned(msg)
  31. return {
  32. pass: warned,
  33. message: warned
  34. ? 'Expected message "' + msg + '" not to have been warned'
  35. : 'Expected message "' + msg + '" to have been warned'
  36. }
  37. }
  38. }
  39. }
  40. // define custom matcher for warnings
  41. beforeEach(() => {
  42. asserted = []
  43. spyOn(console, 'warn')
  44. spyOn(console, 'error')
  45. jasmine.addMatchers({
  46. toHaveBeenWarned: () => createCompareFn(console.error),
  47. toHaveBeenTipped: () => createCompareFn(console.warn)
  48. })
  49. })
  50. afterEach(done => {
  51. const warned = msg => asserted.some(assertedMsg => msg.toString().indexOf(assertedMsg) > -1)
  52. let count = console.error.calls.count()
  53. let args
  54. while (count--) {
  55. args = console.error.calls.argsFor(count)
  56. if (!warned(args[0])) {
  57. done.fail(`Unexpected console.error message: ${args[0]}`)
  58. return
  59. }
  60. }
  61. done()
  62. })