Mock Fetch Post Method

23 Views Asked by At

I am trying to Mock up a POST HTTP request form a pinia store but having no luck. It works within the application but I'm having trouble mocking the post request. below is my current code. I am using vue and vitest. I basically want to be able to call a dummy post end point and set the auth code to 123456. This code doesnt break the tests but it does not set the auth code and i belive it is because the global.fetch is not a post request.

Mock fetch request

global.fetch = vi.fn(() => Promise.resolve({ 
    method: "post",
    status: 200,
    ok: true,
    data: {
        auth_code: 123456
    },
    json: () => Promise.resolve({
        auth_code: 123456
    })
}));

Test

describe('login', (): void => {
    it('logs a user in', async () => {
        const authStore = useAuthStore();

        const {
            email, 
            password,
            loading,
            auth_code
        } = storeToRefs(authStore)

        email.value = dummy_data.email;
        password.value = dummy_data.password;
    
        authStore.login();

        expect(auth_code).toStrictEqual(123456)

    })
})

store action

login() {

    this.loading = true;
    this.loaded = false;
    this.error = false;

    const data: {
        email: string;
        password: string;
    } = {
        email: this.email,
        password: this.password
    };

    return new Promise((resolve, reject): void => {
        ApiService.post(`api/api-test`, JSON.stringify(data))
            .then((response: {[key: string]: string}): void => {
                console.log('login')
                this.loading = false;
                this.loaded = true;
                this.auth_code = 123456;
                resolve(response)
            })
            .catch((response: {[key: string]: string}): void => {
                console.log(response);
                this.loading = false;
                this.loaded = true;
                this.error = response;
                reject(response)
            });
    });
},
0

There are 0 best solutions below