Vue Js – 使用 sinon 模块模拟 $http 请求

huangapple go评论50阅读模式
英文:

Vue Js - mock the $http request using sinon modules

问题

在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);
    });
});

输出:
我得到了步骤1、步骤2、步骤4的日志,但没有得到步骤3、步骤5、步骤6和步骤7。

Vue Js – 使用 sinon 模块模拟 $http 请求

英文:

In VueJs project I have list of api request methods in apiList.ts file with below code. Also I am trying to add the unit test case for getUsers, addUser, updateUser methods but unable to mock the http methods(get/post/put). Could someone help to add the test case for this below code.

File: 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);
    },
}

File: 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);
    });
});

Output:
I am getting the logs step1, step2, step4 but step3, step5, step6 and step7 not getting.

Vue Js – 使用 sinon 模块模拟 $http 请求

答案1

得分: 2

根据你的要求,以下是翻译好的代码部分:

// 首先,我使用 npm 安装 chai 和 sinon
npm install chai sinon --save-dev

// 然后,我在 before() 函数中创建了一个用于 $http 的模拟对象
$httpMock = {
  get: sinon.stub(),
  post: sinon.stub(),
  put: sinon.stub(),
};

// 将模拟对象赋值给 Vue.prototype.$http
Vue.prototype.$http = $httpMock;

// 在每个测试之前,使用 beforeEach() 函数重置存根
$httpMock.get.reset();
$httpMock.post.reset();
$httpMock.put.reset();

// 接下来,你可以这样做
it('API_LISTS.getUsers - 应该调用 $http.get 并传递正确的 URL', () => {
  const expectedUrl = '/get/users';

  // 调用 getUsers 方法
  API_LISTS.getUsers();

  // 断言 $http.get 被调用,并传递了预期的 URL
  assert.isTrue($httpMock.get.calledOnceWith(expectedUrl));
});

it('API_LISTS.addUser - 应该调用 $http.post 并传递正确的 URL 和数据', () => {
  const expectedUrl = '/new/user';
  const requestData = { name: 'John', age: 25 };

  // 调用 addUser 方法
  API_LISTS.addUser(requestData);

  // 断言 $http.post 被调用,并传递了预期的 URL 和数据
  assert.isTrue($httpMock.post.calledOnceWith(expectedUrl, requestData));
});

it('API_LISTS.updateUser - 应该调用 $http.put 并传递正确的 URL 和数据', () => {
  const expectedUrl = '/update/user';
  const requestData = { id: 1, name: 'John' };

  // 调用 updateUser 方法
  API_LISTS.updateUser(requestData);

  // 断言 $http.put 被调用,并传递了预期的 URL 和数据
  assert.isTrue($httpMock.put.calledOnceWith(expectedUrl, requestData));
});

祝你好运!

英文:

In my opinion: first i install chai and sinon with npm

npm install chai sinon --save-dev

after that i create a mock for http on before()

// 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;

And on beforeEach() reset the stbs before each test

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

After that you do this

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));
});

Good luck for you

huangapple
  • 本文由 发表于 2023年5月29日 11:05:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定