我正在尝试用Vitest测试Vue组件,但为了做到这一点,我需要模拟auth0
下面是我的Navbar.test.ts文件,但是当我运行测试时,我一直得到以下错误Cannot read properties of undefined (reading 'mockReturnValue',因为useAuth0似乎是未定义的,即使我是在页面顶部导入它。也许我只是不太理解它的嘲弄面,但任何帮助都会很感激。
import { vi } from 'vitest'
import { ref } from "vue";
import { shallowMount } from '@vue/test-utils'
import { useAuth0 } from '@auth0/auth0-vue';
import NavBar from "@/components/NavBar.vue";
const user = {
email: "user@test.com",
email_verified: true,
sub: ""
};
vi.mock("@auth0/auth0-vue");
const mockedUseAuth0 = vi.mocked(useAuth0, true);
describe("NavBar.vue", () => {
beforeEach(() => {
mockedUseAuth0.mockReturnValue({
isAuthenticated: ref(true),
user: ref(user),
logout: vi.fn(),
loginWithRedirect: vi.fn(),
...
isLoading: ref(false),
});
});
it("mounts", () => {
const wrapper = shallowMount(NavBar, {
props: { },
});
expect(wrapper).toBeTruthy();
});
afterEach(() => vi.clearAllMocks());
});发布于 2022-06-24 00:50:52
嘲弄auth0.useAuth0
若要访问模拟模块,请使用通配符导入整个模块,并避免命名导入。此外,vi.mocked()只是TypeScript支持的助手。它不会嘲笑任何东西。
所以,不是这样的:
import { useAuth0 } from '@auth0/auth0-vue' ❌
vi.mock('@auth0/auth0-vue')
const mockedUseAuth0 = vi.mocked(useAuth0, true) ❌...do这个:
import * as auth0 from '@auth0/auth0-vue' ✅
vi.mock('@auth0/auth0-vue')然后,通过直接将属性附加到模拟的useAuth0导入来模拟auth0:
describe('NavBar.vue', () => {
it('does something', async () => {
(auth0 as any).useAuth0 = vi.fn().mockReturnValue({
// relevant fields for test
});
})
})useAuth0的值应该是一个模拟函数(vi.fn()),用于返回与测试相关的字段。假设被测试的组件是来自Auth0的示例应用程序,您可以编写一个测试来验证登录按钮调用loginWithRedirect。该按钮只有可用的都是假的。注意,这些字段不需要是Vue refs。
所以这样的测试看起来可能是这样的:
describe('NavBar.vue', () => {
it('login button invokes useAuth.loginWithRedirect', async () => {
const loginWithRedirect = vi.fn();
(auth0 as any).useAuth0 = vi.fn().mockReturnValue({
isAuthenticated: false,
isLoading: false,
loginWithRedirect,
});
const wrapper = shallowMount(NavBar);
await wrapper.find('button#qsLoginBtn').trigger('click');
expect(auth0.useAuth0).toHaveBeenCalled();
expect(loginWithRedirect).toHaveBeenCalled();
})
})嘲弄useAuth().user
还可以编写一个测试来验证组件中显示的经过身份验证的用户的详细信息。具体来说,.user-info和.user-info img (当isAuthenticated是真的)。因此,模拟的useAuth0应该返回isAuthenticated和user,如下所示:
describe('NavBar', () => {
it('authenticated user details are shown', async () => {
const user = {
name: 'john@gmail.com',
picture: 'https://s.gravatar.com/avatar/1f9d9a9efc2f523b2f09629444632b5c?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fjo.png',
};
(auth0 as any).useAuth0 = vi.fn().mockReturnValue({
isAuthenticated: true,
user,
});
const wrapper = shallowMount(NavBar);
expect(wrapper.find('.user-info').text()).toBe(user.name);
expect(wrapper.find('.user-info img').attributes('src')).toBe(user.picture);
})
})https://stackoverflow.com/questions/72732768
复制相似问题