使用delayResponse

我有一个登录组件,该组件应该获取用户凭证,将其提交给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
herichcq 回答:使用delayResponse

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3022118.html

大家都在问