【发布时间】:2019-07-14 20:50:31
【问题描述】:
我正在尝试测试我的 axios 调用未获得 200 的 HTTP 响应的情况。当 axios 未获得成功的响应时,它会引发错误。在这种情况下,我想验证 console.log 是否被调用了两次。
这是我正在测试的类的 sn-p:
class App extends React.Component {
...
async componentDidMount() {
let url = "/api/info/tmp"
try {
let response = await axios.get(url);
...do stuff
this.setState(...);
} catch (e) {
console.log("Could not get " + url);
console.log(e);
}
}
...
}
这是我的玩笑测试的 sn-p
let mockAxios = new MockAdapter(axios);
...
describe("App - componentDidMount() behavior test", () => {
beforeEach(() => {
app = shallow(<App />);
})
afterEach(() => {
app = undefined;
mockAxios.reset();
});
...
describe("Get " + url + " HTTP response status is not 200", () => {
beforeAll(() => {
mockAxios.onGet(url).reply(302, mockData);
});
it("Does not set state regardless of response body", () => {
console.log = jest.fn();
const state = app.state();
expect(console.log).toHaveBeenCalledTimes(2);
expect(state.solutions).toEqual({});
expect(state.username).toEqual("");
});
});
});
我知道console.log = jest.fn() 位正在做某事,因为当我设置它时控制台不再记录虚假错误。但是,测试失败,因为Expected mock function to have been called two times, but it was called zero times.
我尝试将console.log = jest.fn() 移动到“beforeEach”、“beforeAll”中,并作为全局变量。
更新
我很确定这与正在发生的所有异步有关。 如果我这样做:
it("Does not set state regardless of response body", async () => {
console.log = jest.fn();
await app.instance().componentDidMount();
expect(console.log).toHaveBeenCalledTimes(2);
const state = app.state();
expect(state.solutions).toEqual({});
expect(state.username).toEqual("");
});
然后测试仍然失败,但我的理由改变了:Expected mock function to have been called two times, but it was called four times. 现在我只是想弄清楚为什么它被调用了四次而不是两次。
更新 2
我知道为什么 console.log 被调用了 4 次!现在我只需要弄清楚我应该如何重构我的测试。 如果我注释掉我的笑话,甚至是整个单元测试
it("Does not set state regardless of response body", async () => {
//const state = app.state();
//expect(state.solutions).toEqual({});
//expect(state.username).toEqual("");
//expect(console.log).toHaveBeenCalledTimes(2);
});
然后我可以在我的控制台中计算出确实已经有两个不同的 console.log 调用。 shallow(<App />) 必须已经在调用 componentDidMount() 或其他东西。当我添加 app.instance().componentDidMount() 时,我可以直观地看到它正在记录 4 次。
【问题讨论】:
标签: javascript reactjs jestjs axios enzyme