【发布时间】: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