vue cli setup reference
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
collectCoverageFrom: [
'src/**/*.{vue,js}',
'!src/main.js',
'!src/shared/*',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest',
},
moduleNameMapper: {
'^@/test(.*)$': '<rootDir>/test/$1',
'^@/(.*)$': '<rootDir>/src/$1',
},
snapshotSerializers: ['jest-serializer-vue'],
testMatch: [
'**/test/unit/**/*.spec.(js|jsx|ts|tsx)|**/__test__/*.(js|jsx|ts|tsx)',
],
testURL: 'http://localhost/',
};
Vue file to test
Using mocha/chai/sinon
😬
Using mocha/chai/sinon (cont'd)
Using Jest
😮
// sinon:
vm.$store.dispatch = sandbox.stub();
// Jest:
vm.$store.dispatch = jest.fn();
// chai:
expect(vm.property).to.be.true;
expect(vm.property).to.equal(1);
expect(vm.property).to.deep.equal({ prop: "1" });
// Jest:
expect(vm.$store.dispatch).toEqual(true);
expect(vm.$store.dispatch).toEqual(1);
expect(vm.$store.dispatch).toEqual({ prop: "1" });
// chai:
expect(vm.$store.dispatch).to.have.been.calledOnce;
// Jest:
expect(vm.$store.dispatch).toHaveBeenCalledTimes(1);
method in vue
Jest test
Jest runs really fast, and I like how straightforward it is. There isn't much "magic" involved; you have to explicitly state everything you're passing into it, and doesn't do much for you. I'm not a fan of how .only and .skip don't work properly, however - the documentation says it should work, but there are a few stackoverflow questions opened about it and in my own testing I haven't seen it work correctly. I think the snapshots feature would be cool if we can find a good way to use it, but until then, it just kind of gets in the way of doing reliable searches.
The thing that is "magic" about Jest is that it looks like it's handling a lot behind the scenes when it comes to running the tests quickly, like breaking them up into suites and running in parallel. This is great, and makes them run lightning fast, but it also means that if something breaks with that async magic it's going to be really hard to debug.
I really like how we don't have to use sinon, and the spy/stub logic in jest seems less bloated and full of things we don't need/use. That being said, I still like using the piecemeal solution of separate, small, easy-to-use and ubiquitous libraries as opposed to the one solution that jest brings. Having different small parts makes them easier to replace individually, and the drawbacks listed previously can be a real pain.
It's clear that jest has a lot of traction in the community, and should be considered for new projects;
however, I don't think it has enough plusses to warrant changing our existing projects that use Vue to the Jest framework.