如何在Jest中模拟AWS Amplify?

时间:2020-05-26 00:54:01

标签: unit-testing vue.js jestjs aws-amplify vue-test-utils

我正在使用Vue创建一个应用程序,并使用Vue Test Utils和Jest作为单元测试框架。但是,在测试方案时,在登录失败时应显示无效的凭据时遇到了一个问题。我想知道如何模拟AWS Amplify的Auth。我不太确定自己是否正确地进行测试,因为我是前端单元测试的新手。

Login.vue:

import { Auth } from 'aws-amplify'
import { required } from 'vuelidate/lib/validators'

export default {
  name: 'loginComponent',
  data() {
    return {
      form: {
        email: null,
        password: null,
      },
      authErrMsg: '',
      isShowAuthErr: false,
      isLoading: false,
    }
  },
  validations: {
    form: {
      email: { required },
      password: { required }
    }
  },
  methods: {
    validateState(name) {
      const { $dirty, $error } = this.$v.form[name];
      return $dirty ? !$error : null;
    },
    onSubmit() {
      this.$v.$touch();
      if (this.$v.$invalid) {
        return
      }

      this.isLoading = true
      this.isShowAuthErr = false
      const { email, password } = this.form
      Auth.signIn(email, password).then(() => {
          this.isLoading = false
          this.$store.dispatch('ACTION_SET_LOGGEDIN_STATUS', true)
          this.$router.push({ name: 'home' })
      }).catch(() => {
          this.isLoading = false
          this.authErrMsg = 'Invalid login credentials'
          this.$store.dispatch('ACTION_SET_LOGGEDIN_STATUS', false)
          this.isShowAuthErr = true
      })

    }
  }
}

Login.spec.js:

import { mount, shallowMount, createLocalVue } from '@vue/test-utils'
import Login from '@/components/Login'
import BootstrapVue from 'bootstrap-vue'
import Vuelidate from 'vuelidate'
import Vuex from 'vuex'
import Auth from '@aws-amplify/auth'
import flushPromises from 'flush-promises'

const localVue = createLocalVue()
localVue.use(BootstrapVue)
localVue.use(Vuelidate)
localVue.use(Vuex)
localVue.use(Auth)

let wrapper
beforeEach(() => {
  wrapper = mount(Login, { localVue, 
    form: {
      email: null,
      password: null,
    }
  })
})

describe('Login', () => {

  it('should error message on failed login', async () => {
    wrapper.find('input[name="email"]').setValue('email@gmail.com')
    wrapper.find('input[name="password"]').setValue('123ABC')
    wrapper.find("form").trigger("submit.prevent")
    await flushPromises()
    Auth.signIn = jest.fn().mockImplementation(() => {
      throw new Error('Incorrect username or password.')
    });
    expect(Auth.signIn()).rejects.toThrow()
  })

})

我得到的错误:

TypeError:无法读取未定义的属性“ clientMetadata”

0 个答案:

没有答案