[1.基本用法]
[1.1断言库]
[1.2如何处理异步]
[1.3使用mock function]
[2.Vue相关的测试]
[1.1Vue DOM测试]
[1.2Vue 事件测试]
[1.3Vue 处理请求]
基本用法 -- 断言库
// be and equal
expect(4 * 2).toBe(8); // ===
expect({bar: 'bar'}).toEqual({bar: 'baz'}); // deep equal
expect(1).not.toBe(2);
// boolean
expect(1 === 2).toBeFalsy();
expect(false).not.toBeTruthy();
// comapre
expect(8).toBeGreaterThan(7);
expect(7).toBeGreaterThanOrEqual(7);
expect(6).toBeLessThan(7);
expect(6).toBeLessThanOrEqual(6);
// Promise
expect(Promise.resolve('problem')).resolves.toBe('problem');
expect(Promise.reject('assign')).rejects.toBe('assign');
// contain
expect(['apple', 'banana']).toContain('banana');
expect([{name: 'Homer'}]).toContainEqual({name: 'Homer'});
// match
expect('NBA').toMatch(/^NB/);
expect({name: 'Homer', age: 45}).toMatchObject({name: 'Homer'});
测试异步代码
// Don't do this!
test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter');
}
fetchData(callback);
});
这样的代码不不会生效,因为jest默认代码执行到最后就结束了。 需要改写成
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
github.com/facebook/je…tests/user.test.js
这个的问题是不会捕获到错误
使用promise
test('the data is peanut butter', () => {
expect.assertions(1);
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
test('the data is peanut butter', () => {
expect.assertions(1);
return expect(fetchData()).resolves.toBe('peanut butter');
});
使用mock function
mock function 的用途:
- 检测函数有没有被调用,可以通过mockCallback.mock.calls[0][0] 获取回调的参数
const mockCallback = jest.fn();
forEach([0, 1], mockCallback);
// The mock function is called twice
expect(mockCallback.mock.calls.length).toBe(2);
// The first argument of the first call to the function was 0
expect(mockCallback.mock.calls[0][0]).toBe(0)
- mock时间,一些有时间操作的代码,需要通过时间mock来快速前进或者后退
具体demo
[1.1Vue DOM测试]
* 通过使用组件来考察组件的用法
```
it('agree 原型按钮(默认)', () => {
vm = createVue({
template: `
<agree :value='true' v-model='isAgree'></agree>
`,
data () {
return {
isAgree: false
}
}
});
triggerClick(vm.$el.firstChild, true, false)
expect(vm.isAgree).toEqual(true)
})
```
* 事件处理可以通过mock函数来占位
```
const mockCallback = jest.fn()
wrapper = mount(
compileToFunctions(`<dynamic-code track-name="{name:'sendDynamicCode'}" @click="clickdynamiccodeWay"></dynamic-code>`),
{
methods: {
clickdynamiccodeWay: mockCallback
}
}
)
```
[1.2 处理请求]
处理请求一般是直接mock数据 也可以在setup.js指定的apiMock.js里统一mock,但是统一的mock是应该根据local.js里的proxyHost来代理发送nodejs请求 *
localVue.prototype.$Api[api] = function ({resolve}) {
return Promise.resolve().then(() => {
resolve.call(this, {
boolen: 1,
data: data
})
parentResolve()
})
}
- 或者通过统一的mock请求
[vue-test-utils.vuejs]
这个是VUE专门的测试工具包,解决了VUE单元测试的几个问题:
- VUE异步渲染的问题。通过内置的API,setData,triggerClick 默认加上强制更新的方式,来保证,在部分业务场景中仍需要手动使用wrapper.update方式更新
- 提供了shallow方法,mount方法是VUE默认的方法,shallow方法是把代码中的组件部分的render函数直接替换成空,可以直接检测某个组件是否存在,同时展示出来的代码量也比较少
- createLocalVue方法,返回一个 Vue 的类供你添加组件、混入和安装插件而不会污染全局的 Vue 类
参考资料: