简体   繁体   English

需要测试axios Web服务保证在Vue.js应用中使用Jest返回结果

[英]Need to test axios web service promises return result using Jest in Vue.js app, but getting error

I am developing new application using Vue.js and axios, to get stock market details based upon company name. 我正在使用Vue.js和axios开发新的应用程序,以根据公司名称获取股票市场详细信息。 At the start of application, I am gathering all the US based S&p 500 company's name into javascript array 在应用程序开始时,我将所有位于美国的S&p 500公司的名称收集到javascript数组中

 <script> import axios from 'axios' import StockInfo from './StockInfo.vue' export default { name: 'app', data () { return { stockname : "", resultArrived : false, fetchStatus: false, resultDetails: { Symbol : '', LastUpdated: '', Open : '', Close : '', High : '', Low : '', DividendAmount : 0.0 }, errorMessage : '', stockdetails : [] } }, components : { 'stockdetails' : StockInfo }, created : function() { this.LoadStockData(); }, methods: { LoadStockData : function() { var basicUrl = "https://api.iextrading.com/1.0/ref-data/symbols"; var self = this; axios.get(basicUrl).then(result => { // Make sure that we receive proper result let smallset = []; result.data.filter(function(record) { if(record.type === "cs") { // Convert string to lower case let finalvalue = self.GetProperCompanyName(record.name); let updatedvalue = { Symbol : record.symbol, Name : finalvalue }; smallset.push(updatedvalue); return updatedvalue; } }); this.stockdetails = smallset; }, error => { this.errorMessage = error.message; this.resultArrived = false; this.fetchStatus = true; }); }, } } </script> describe('User input Scenario', () => { jest.mock('axios'); it('App should be mounted',async () => { const appwrapper = mount(app); await appwrapper.vm.$nextTick(); expect(axios.get).toHaveBeenCalledWith('https://api.iextrading.com/1.0/ref-data/symbols'); expect(appwrapper.vm.stockdetails.length).toBeGreaterThan(0); }); }); 

Now I want to unit test this scenario using jest and testutil, so I written following test case 现在,我想使用jest和testutil对这种情况进行单元测试,因此我编写了以下测试用例

describe('User input Scenario', () => {
    jest.mock('axios');

    it('App should be mounted',async () => {
        const appwrapper = mount(app);
        await appwrapper.vm.$nextTick();

        expect(axios.get).toHaveBeenCalledWith('https://api.iextrading.com/1.0/ref-data/symbols');
        expect(appwrapper.vm.stockdetails.length).toBeGreaterThan(0);
    });

});

But when I ran this test case, I am getting following errors 但是,当我运行此测试用例时,出现以下错误

FAIL ./App.test.js ● User input Scenario › App should be mounted FAIL ./App.test.js●用户输入场景›应安装应用程序

expect(jest.fn())[.not].toHaveBeenCalledWith()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function wrap]

  63 |         await appwrapper.vm.$nextTick();
  64 |
> 65 |         expect(axios.get).toHaveBeenCalledWith('https://api.iextrading.com/1.0/ref-data/symbols');
     |                           ^
  66 |         expect(appwrapper.vm.stockdetails.length).toBeGreaterThan(0);
  67 |     });
  68 |

  at toHaveBeenCalledWith (App.test.js:65:27)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:296:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
  at step (App.test.js:23:191)
  at App.test.js:23:361

Test Suites: 1 failed, 1 passed, 2 total Tests: 1 failed, 7 passed, 8 total Snapshots: 0 total Time: 5.328s 测试套件:1个失败,1个通过,总共2个测试:1个失败,7个通过,总共8个快照:0个总时间:5.328s

Maybe need import axios in test file also 也许还需要在测试文件中导入axios

import axios from 'axios';

And try to mock get method of it 并尝试模拟它的获取方法

axios.get.mockResolvedValue({data: 'something'});

Example in Jest: https://jestjs.io/docs/en/mock-functions#mocking-modules Jest中的示例: https : //jestjs.io/docs/en/mock-functions#mocking-modules

Also exist separate npm packages for mock axios during testing jest-mock-axios or similar 在测试jest-mock-axios或类似产品时,还存在用于模拟axios的单独的npm软件包

 Александр Смышляев Second part of answer did the trick, for axios, it need mocking with expected result value jest.mock('axios', () => ({ get: jest.fn() })); describe("Basic App.vue Layout Verification", () => { let appwrapper; beforeEach(() => { axios.get.mockClear(); axios.get.mockReturnValue(Promise.resolve({})); }); it('App Mounting verfication',async () => { // Given const result = { data : [{ symbol: "A", name: "Agilent Technologies Inc.", date: "2018-12-28", isEnabled: true, type: "cs", iexId: "2" }, { symbol: "A", name: "Agilent Technologies Inc.", date: "2018-12-28", isEnabled: true, type: "cs", iexId: "2" }, { symbol: "A", name: "Agilent Technologies Inc.", date: "2018-12-28", isEnabled: true, type: "cs", iexId: "2" }, { symbol: "A", name: "Agilent Technologies Inc.", date: "2018-12-28", isEnabled: true, type: "cs", iexId: "2" } ]}; axios.get.mockReturnValue(Promise.resolve(result)); const appwrapper = mount(app); await appwrapper.vm.$nextTick(); expect(axios.get).toHaveBeenCalledWith('https://api.iextrading.com/1.0/ref-data/symbols'); expect(appwrapper.vm.stockdetails.length).toBeGreaterThan(0); expect(typeof appwrapper.vm.stockdetails).toEqual("object"); // Now validate actual result parsed by webservice return value expect(appwrapper.vm.stockdetails[0].Symbol).toEqual("A"); expect(appwrapper.vm.stockdetails[0].Name).toEqual("agilent technologies"); }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM