需要测试axios Web服务承诺使用Vue.js应用中的Jest返回结果,但是会出错

时间:2018-12-29 12:58:51

标签: javascript web-services vue.js axios jestjs

我正在使用Vue.js和axios开发新的应用程序,以根据公司名称获取股市详细信息。在应用程序开始时,我正在将所有美国标准普尔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);
    });

});

现在,我想使用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);
    });

});

但是当我运行此测试用例时,出现以下错误

失败./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

测试套件:1个失败,1个通过,总共2个 测试:1个失败,7个通过,总共8个 快照:共0个 时间:5.328秒

2 个答案:

答案 0 :(得分:0)

也许还需要在测试文件中导入axios

import axios from 'axios';

并尝试模拟它的get方法

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

笑话中的示例:https://jestjs.io/docs/en/mock-functions#mocking-modules

在测试 jest-mock-axios 或类似

期间,还存在用于模拟axios的单独的npm软件包。

答案 1 :(得分:0)

Александр Смышляев

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