我有一个登录组件,它应该获取用户凭据,将它们提交给 API,并根据响应在 VueX 商店中设置 JWT 或显示错误。
在单元测试中,我正在模拟 axios 调用,其响应延迟以模拟实际网络(使用 axios-mock-adapter 库)。目前,测试失败,因为尽管我正在使用flushPromises()
实用程序,但测试在承诺解决之前完成。事实上,我没有看到console.log
登录功能中的任何一个。
如果我delayResponse
从模拟调用中删除该属性,则测试通过,并且我在控制台日志中看到了预期的“获取数据”响应。
我在这里想念什么?有谁知道为什么flushPromises()
只是跳过 axios 调用?
我正在使用 Vuetify 框架,因此使用了v-
标签,尽管我怀疑这会对测试产生影响
模板:
<v-alert
type="error"
:value="!!error"
test-id="LoginError"
v-html="error"
/>
<form
@submit.prevent="login"
test-id="LoginForm"
>
<v-text-field
label="Email Address"
test-id="LoginEmailField"
v-model="credentials.email"
/>
<v-text-field
label="Password"
type="password"
test-id="LoginPasswordField"
v-model="credentials.password"
/>
<v-btn
type="submit"
test-id="LoginSubmitBtn"
>
Login
</v-btn>
</form>
登录功能相当简单:
async login() {
try {
const response = await axios.post(this.url, this.credentials);
console.log('got response', response);
const token = response.data.payload;
this.$store.dispatch('setUser', { token });
} catch (error) {
console.warn('caught error', error);
this.error = error;
}
}
测试文件:
fit('Receives and stores JWT in the VueX store after sending valid credentials', async () => {
const maxios = new AxiosMockAdapter(axios, {delayResponse: 100});
const validData = { email: 'aa@bb.cc', password: '111' };
const validToken = 'valid-token';
maxios.onPost().reply(200, { payload: validToken });
wrapper.find('[test-id="LoginEmailField"]').vm.$emit('input', validData.email);
wrapper.find('[test-id="LoginPasswordField"]').vm.$emit('input', validData.password);
wrapper.find('[test-id="LoginSubmitBtn"]').trigger('click');
await flushPromises();
expect(localStore.state.user.token).toBe(validToken);
});
VueX 商店:
export const state = {
user: {
token: null,
},
};
const mutations = {
SET_USER: (currentState, user) => {
currentState.user = user;
},
};
const actions = {
setUser: ({ commit }, payload) => {
commit('SET_USER', payload);
},
};
export const mainStore = {
state,
mutations,
actions,
};
export default new Vuex.Store(mainStore);
响应:
expect(received).toBe(expected) // Object.is equality
Expected: "valid-token"
Received: null