【问题标题】:Jasmine: Testing that a method passed in as an argument to another method gets runJasmine:测试作为参数传入另一个方法的方法是否运行
【发布时间】:2021-09-16 19:22:52
【问题描述】:

我的代码如下

//agency_controller.js
import axios from 'axios';

export const getProducerNamesAndBillingPlan = ({ agencyId = '', onSuccess= (x) => x } = {} )  => {
  if(!!agencyId) {
    axios.get('/agency/' + agencyId)
         .then(response => onSuccess.call(this, response['data']))
         .catch(error => console.error(error))
  }
}
//agency_controller.spec.js
import { getProducerNamesAndBillingPlan } from "../../../../app/javascript/packs/controllers/agencies_controller";
import axios from 'axios';

const mockAxiosPromise = (response) => {
  return new Promise((resolve, _reject) => {
    resolve({ status: 200, data: response});
  });
}

describe('#getProducerNamesAndBillingPlan', () => {
...
it('calls the given onSuccess method if the request is successful', () => {
    spyOn(axios, 'get').and.callFake(() => {
      return mockAxiosPromise('foo')
    })

    const mockMethod = (x) => console.log(x)

    spyOn(console.log, 'call')

    getProducerNamesAndBillingPlan({ agencyId: 1, onSuccess: mockMethod })

    expect(console.log.call).toHaveBeenCalledWith('foo')
  })
})

我可以看出代码正在运行,因为当我运行测试时,'foo' 被记录到控制台。但是测试仍然失败:

#getProducerNamesAndBillingPlan calls the given onSucess method if the request is sucessful FAILED
        Expected spy call to have been called with [ 'foo' ] but it was never called.
            at UserContext.<anonymous> (spec/javascripts/packs/controllers/agencies_controller.spec.js:1:17348)

expect(console.log).toHaveBeenCalledWith('foo') 也是如此。我做错了吗?

【问题讨论】:

    标签: javascript unit-testing axios jasmine karma-jasmine


    【解决方案1】:

    axios.get() 方法返回一个 promise,但 getProducerNamesAndBillingPlan 函数不返回它。您在测试用例中调用它。当代码执行expect语句时,promise没有被解析或拒绝,所以你的onSuccess方法在断言之前没有被调用。

    在测试用例中使用async/await 以确保在断言之前已解决或拒绝承诺。

    agency_controller.js:

    import axios from 'axios';
    
    export const getProducerNamesAndBillingPlan = ({ agencyId = '', onSuccess = (x) => x } = {}) => {
      if (!!agencyId) {
        return axios
          .get('/agency/' + agencyId)
          .then((response) => onSuccess.call(this, response['data']))
          .catch((error) => console.error(error));
      }
    };
    

    agency_controller.spec.js:

    import axios from 'axios';
    import { getProducerNamesAndBillingPlan } from './agency_controller';
    
    describe('#getProducerNamesAndBillingPlan', () => {
      it('calls the given onSuccess method if the request is successful', async () => {
        spyOn(axios, 'get').and.resolveTo({ status: 200, data: 'foo' });
        const mockMethod = (x) => console.log(x);
        spyOn(console, 'log');
        await getProducerNamesAndBillingPlan({ agencyId: 1, onSuccess: mockMethod });
        expect(console.log).toHaveBeenCalledWith('foo');
      });
    });
    

    测试结果:

    Executing 1 defined specs...
    Running in random order... (seed: 00239)
    
    Test Suites & Specs:
    
    1. #getProducerNamesAndBillingPlan
       ✔ calls the given onSuccess method if the request is successful (5ms)
    
    >> Done!
    
    
    Summary:
    
    ?  Passed
    Suites:  1 of 1
    Specs:   1 of 1
    Expects: 1 (0 failures)
    Finished in 0.01 seconds
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      相关资源
      最近更新 更多