我有一个简单的Vue组件,该组件会在创建API密钥时获取API密钥,并且可以通过单击按钮来更新密钥:
<template>
<div>
<div>{{data.api_key}}</div>
<button ref="refresh-trigger" @click="refreshKey()">refresh</button>
</div>
</template>
<script>
export default {
created() {
axios.get(this.url).then((response) => {
this.data = response.data
})
}
methods: {
refreshKey() {
axios.put(this.url).then((response) => {
this.data = response.data
})
},
}
}
</script>
我想用以下代码对其进行测试:
import {shallowMount} from '@vue/test-utils';
import axios from 'axios';
import apiPage from '../apiPage';
jest.mock('axios');
describe('API page', () => {
it('should fetch API key on component creation', done => {
const initialData = {
api_key: 'initial_API_key',
};
const newData = {
api_key: 'new_API_key',
};
axios.get.mockImplementationOnce(() =>
Promise.resolve({
data: initialData,
})
)
axios.put.mockImplementationOnce(() =>
Promise.resolve({
data: newData,
})
);
const wrapper = shallowMount(apiPage);
expect(wrapper.vm.$data.data.api_key).toBeFalsy();
wrapper.vm.$nextTick(() => {
expect(wrapper.vm.$data.data.api_key).toEqual(initialData.api_key);
done()
});
wrapper.find({ref: 'refresh-trigger'}).trigger('click');
wrapper.vm.$nextTick(() => {
expect(wrapper.vm.$data.data.api_key).toEqual(newData.api_key)
done()
})
});
})
但是事实证明,只有第一个值会被模拟,因为我收到了:
[Vue warn]: Error in nextTick: "Error: expect(received).toEqual(expected)
Difference:
- Expected
+ Received
- new_API_key
+ initial_API_key"
found in
---> <Anonymous>
<Root>
console.error node_modules/vue/dist/vue.runtime.common.dev.js:1883
{ Error: expect(received).toEqual(expected)
我在做什么错?也许有一些方法可以检查是否调用了创建的回调,并且其中的所有异步函数都已完成?