我正在尝试使用Jest来模拟Axios,但是我并没有取得太大的成功。我想避免使用单独的程序包(jest-mock-axios),以便对Jest模拟过程更加熟悉。该项目是使用最新版本的create-react-app(v2.1.1)制作的。我还利用酶进行测试。
我目前在使axios模拟工作上遇到问题。这是相关代码和入门测试的摘要(一旦我确定问题出在哪里,测试逻辑就会更新):
App.js
import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentPhase: null,
};
this.hashcodeResults = '';
this.transcriptionData = '';
this.handleFileSelectionSubmit.bind(this);
}
handleFileSelectionSubmit(event) {
event.preventDefault();
const audioData = [];
const targetFile = event.target[0].files;
const fileInfo = {
lastModifiedDate: targetFile[0].lastModifiedDate,
name: targetFile[0].name,
path: targetFile[0].path,
size: targetFile[0].size,
type: targetFile[0].type,
};
audioData.push(fileInfo);
axios({
method: 'post',
url: `${baseUrl}/hash`,
data: {
audioFiles: audioData,
},
})
.then((response) => {
if (response.data.inDatabase === false) {
this.hashcodeResults = response.data.result;
this.setState({
currentPhase: 'hashCodeGenerated',
});
} else {
this.hashcodeResults = response.data.result;
this.transcriptionData = response.data.transcript;
this.setState({
currentPhase: 'transcriptionDownloadComplete',
});
}
})
.catch((error) => {
throw new Error('ERROR (Hashcode Generation): ', error);
});
}
export default App;
App.test.js:
import React from 'react';
import { shallow } from 'enzyme';
import axios from 'axios';
import App from '../App';
jest.mock('axios');
describe('Application audio file submission', () => {
describe('Files that have not been previously transcribed', () => {
it('Should return data', () => {
const response = { data: true };
axios.post.mockResolvedValue(response);
const wrapper = shallow(<App />);
const inst = wrapper.instance();
const fakeEvent = {
preventDefault: () => true,
target: [{
files: 'someFile',
lastModifiedDate: 'someDate',
name: 'someName',
path: 'somePath',
type: 'someType',
}],
};
inst.handleFileSelectionSubmit(fakeEvent).then(res => expect(res.data).toBeDefined());
});
});
});
我运行测试时,看到的错误是“ TypeError:无法读取未定义的属性'then'”,并且指向App.js文件的handleFileSelectionSubmit函数内的axios调用。
任何指导将不胜感激!