vue.js - Vue Js - 使用 sinon 模块模拟 $http 请求

标签 vue.js unit-testing vuejs3 spy

在 VueJs 项目中,我在 apiList.ts 文件中有 api 请求方法列表,代码如下。另外,我尝试添加 getUsers、addUser、updateUser 方法的单元测试用例,但无法模拟 http 方法(get/post/put)。有人可以帮忙添加以下代码的测试用例吗?

文件:apiList.ts

import Vue from 'vue';

export const API_LISTS = {
    getUsers: () => {
        const apiUrl = `/get/users`;
        return Vue.prototype.$http.get(apiUrl);
    },
    addUser: (requestData: any) => {        
        let apiUrl = `/new/user`;
        return Vue.prototype.$http.post(apiUrl, requestData);
    },
    updateUser: (requestData: any) => {
        const url = `/update/user`;
        return Vue.prototype.$http.put(url, requestData);
    },
}

文件:apiLists.spec.ts

    import { assert } from 'chai';
    import {API_LISTS } from 'apiList';
    
    describe.only('getUsers', () => {
    console.log("---------------------------------step-1");
    let axiosGetStub: any;
    const responseData = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];

    beforeEach(() => {
        console.log("---------------------------------step-2");
        axiosGetStub = sinon.stub(Vue.prototype.$http, 'get').callsFake(() => Promise.resolve({ status: 200, data: responseData }));
        console.log("---------------------------------step-3");
    });

    afterEach(() => {
        console.log("---------------------------------step-4");
        axiosGetStub.restore();
    });

    it('should call $http.get with the correct endpoint', async () => {
        console.log("---------------------------------step-5");
        await API_LISTS.getUsers();
        expect(axiosGetStub.calledOnce).equal(true);
        // expect(axiosGetStub.calledWith('/users')).equal(true);
    });

    it('should return the response data', async () => {
        console.log("---------------------------------step-6");
        const result = await API_LISTS.getUsers();
        console.log("---------------------------------step-7");
        // expect(result).equal(responseData);
    });
});

输出: 我收到了日志 step1、step2、step4,但 step3、step5、step6 和 step7 没有收到。

enter image description here

最佳答案

我认为:首先我使用 npm 安装 chai 和 sinon

npm install chai sinon --save-dev

之后我在 before() 上创建了一个 http 模拟

// Create a mock for $http
$httpMock = {
  get: sinon.stub(),
  post: sinon.stub(),
  put: sinon.stub(),
};

// Assign the mock to Vue.prototype.$http
Vue.prototype.$http = $httpMock;

在 beforeEach() 上,在每次测试之前重置 stbs

$httpMock.get.reset();
$httpMock.post.reset();
$httpMock.put.reset();

之后你就这样做

it('API_LISTS.getUsers - should call $http.get with the correct URL', () => {
const expectedUrl = '/get/users';

// Invoke the getUsers method
API_LISTS.getUsers();

// Assert that $http.get was called with the expected URL
assert.isTrue($httpMock.get.calledOnceWith(expectedUrl));
});

it('API_LISTS.addUser - should call $http.post with the correct URL and data', () => {
const expectedUrl = '/new/user';
const requestData = { name: 'John', age: 25 };

// Invoke the addUser method
API_LISTS.addUser(requestData);

// Assert that $http.post was called with the expected URL and data
assert.isTrue($httpMock.post.calledOnceWith(expectedUrl, requestData));
});

it('API_LISTS.updateUser - should call $http.put with the correct URL and data', () => {
const expectedUrl = '/update/user';
const requestData = { id: 1, name: 'John' };

// Invoke the updateUser method
API_LISTS.updateUser(requestData);

// Assert that $http.put was called with the expected URL and data
assert.isTrue($httpMock.put.calledOnceWith(expectedUrl, requestData));
});

祝你好运

关于vue.js - Vue Js - 使用 sinon 模块模拟 $http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76354458/

相关文章:

javascript - 如何使用 Microsoft Graph 对 Vue.js 渐进式 Web 应用进行身份验证

javascript - 直达 |在实体 ListView 中维护默认列的选项

javascript - Vue.js - 更改除单击元素之外的所有元素的颜色

angular - Angular 5 中用于单元测试的语言环境文件

vue.js - Vue3 在 vi​​test 中使用 vuex 测试组合 API

html - 未捕获的 TypeError : Vue. 使用不是函数

javascript - 检查观察者是否包含某些元素

ruby - 我该如何分析 ruby​​ 单元测试的执行情况?

django - 你如何跳过 Django 中的单元测试?

typescript - 如何在开发模式下使用 typescript 在 vue 3 中启用 devtools