How to test when using custom plugins with inject (vue composition) #1698
Replies: 4 comments 2 replies
-
Hi @MaelAbgrall If you want to test something that relies on provide/inject, then you must test it in the context of a component. So for example you can create a test component that you then mount in your test. I hope that helps. If that's not the case, then try to make a reproduction so we can take a look, with a simplified version of what you want, and a unit test that is falling. You can use |
Beta Was this translation helpful? Give feedback.
-
Thank @cexbrayat My test actually look like this (sorry for not putting it in the question) describe("Notifications tests", () => {
let store;
let mockedRouter;
beforeEach(() => {
store = createStore({...});
mockedRouter = {
push: jest.fn(),
};
});
test("the notification page shows notifications", async () => {
axios.mockImplementation(() => Promise.resolve(twoNotifications));
const wrapper = mount(Notifications, {
global: {
plugins: [store, router],
provide: { auth: auth },
},
});
await flushPromises();
const notifications = wrapper.findAll("#notification");
expect(notifications.length).toBe(2);
});
} Is this what you said by context of a component? I forgot to mention, I actually don't need the plugin at all. // auth.js
export function useAuth() {
return inject("auth");
} |
Beta Was this translation helpful? Give feedback.
-
Yes that's what I was referring to, I was not sure you were using a component in your test. It's hard to say what you're missing, I don't see anything obvious (but I don't see how you defined I'll move this to discussions, as it doesn't look like this is an issue with VTU |
Beta Was this translation helpful? Give feedback.
-
@cexbrayat Thanks! I'm struggling to understand how the inject/provide works in the tests, and I'm almost sure this is the root of the issue |
Beta Was this translation helpful? Give feedback.
-
Hello,
I wrote a custom plugin for my app to handle SSO with multiple providers, everything was working fine for the option API, and I'm slowly moving the project to the composition API.
The plugin is simply a class that is made available everywhere.
(auth.js)
and here is an example of a component (to mark a notification as seen) that use the plugin
My first issue is that test are telling me auth is not defined (see below), and I'm getting a vue warning "[Vue warn]: inject() can only be used inside setup() or functional components."
The second issue is that I need to mock this
getToken
method to return an empty string, and I can't figure how to do thatI'm missing something, but I can't get what it is, can anyone explain this?
Beta Was this translation helpful? Give feedback.
All reactions