houtenjack
houtenjack

Reputation: 43

Vue test reporter shows expected thrown error

I am testing if a component throws an error, the test passes as intended, still the reporter outputs the thrown error. Is there a way to prevent this? I don't want to see the expected errors in my test output.

The application was generated using Vue CLI and I run the tests using npm run test:unit which corresponds to vue-cli-service test:unit.

I tried running vue-cli-service manually and passing -q and different reporters as per docs linked by vue-cli-service test:unit --help and they don't seem to work at all (no quiet run, no different reporter).

I am using mocha/chai.

My component's script

export default {
  props: {
    foo: Array,
  },
  mounted() {
    this.bar();
  },
  methods: {
    bar() {
      if(this.foo.length === 0) {
        throw new Error("Array is empty");
      }
    }
  }
}

The test

describe('Component'), () => {
  let localVue;
  beforeEach(() => {
    localVue = createLocalVue();
    localVue.use(Vuetify);
  });
  
  it('throws an error if array is empty', () => {
    const items = [];
    
    const params = {
      locaVue,
      propsData: { foo: items },
    };
    
    const msg = "Array is empty";
    
    // shows error in console both with this statement
    expect(shallowMount.bind(shallowMount, Component, params)).to.throw(msg);
    
    // and this statement
    expect(() => shallowMount(Component, params)).to.throw(msg);
  });
});

Upvotes: 2

Views: 1124

Answers (1)

papiro
papiro

Reputation: 2365

I am the same way in that I don't like a bunch of noise in my test output. What I do is temporarily reassign console.error and then assign it back. Try:

// store a reference to the original function
const originalConsoleError = console.error;
// reassign to a no-op
console.error = () => {};
/** 
 * run tests
*/
// restore to aid in debugging further tests
console.error = originalConsoleError;

Upvotes: 2

Related Questions