我正在编写一个脚本(请参阅下文),以确保axios函数在收到特定状态代码时会引发错误。但是我发现,即使我使该测试失败,Jest仍然说该测试通过了,即使它在控制台中返回了错误(请参阅下文)。为什么开玩笑说这个测试实际上失败了就通过了?它是否与我期望发生错误有关,所以即使测试失败,但仍会收到一个错误(测试失败)并认为这意味着我达到了我的预期?谢谢。
foo.test.js:
import axios from 'axios';
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve({ data: 'payload' })),
}));
const getData = async (url) => {
const response = await axios.get(url);
if (response.status !== 200) {
return response.text().then((error) => {
throw new Error(error.message);
});
} else {
return response.data;
}
};
test('testing that an error is thrown', async () => {
axios.get.mockImplementation(() =>
Promise.resolve({
data: {data: 'payload'},
status: 400,
text: () => Promise.resolve(JSON.stringify({message: 'This is an error.'})),
})
);
const expectedError = async () => {
await getData('sampleUrl');
};
// The error should return 'This is an error.' and instead
// is expecting 'foo', so this test should fail.
expect(expectedError()).rejects.toThrowError('foo');
});
答案 0 :(得分:1)
您需要进行两项更改才能使测试按预期失败。
text
中的解析值进行字符串化处理await
使用rejects
的expect
这是更新的版本,按预期失败:
import axios from 'axios';
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve({ data: 'payload' })),
}));
const getData = async (url) => {
const response = await axios.get(url);
if (response.status !== 200) {
return response.text().then((error) => {
throw new Error(error.message);
});
} else {
return response.data;
}
};
test('testing that an error is thrown', async () => {
axios.get.mockImplementation(() =>
Promise.resolve({
data: {data: 'payload'},
status: 400,
text: () => Promise.resolve({message: 'This is an error.'}), // <= don't stringify
})
);
const expectedError = async () => {
await getData('sampleUrl');
};
await expect(expectedError()).rejects.toThrowError('foo'); // <= await
});