javascript - 使用 jest 在 Promise 中测试异步函数
问题描述
我有一段代码一直在努力测试。这是一个承诺,在这个承诺中还有另一个异步函数。例如:
export const myFunc = () =>
new Promise ((resolve, reject) =>
anAsyncFun()
.then(response => axios.post(response))
.then(response => doSomething(response))
.catch(err)
)
我如何告诉 jest 从 'anAsyncFunc()' 返回一个特定值并将该值传递给函数的下一步。这是实际功能
export const refreshAuth = () =>
new Promise((resolve, reject) =>
getRefreshToken()
.then(refreshJWT =>
axios.post(`${BlindlyApi.auth}/refresh`, {
refreshJWT
})
)
.then((res: AxiosResponse<JWTData>) => {
onSignIn(res.data.accessJWT, res.data.refreshJWT);
resolve(res.data.accessJWT);
})
.catch(err => {
console.error('failed to refresh the access token', err);
reject(err);
})
);
这就是我现在要测试的内容。
import axios from 'axios';
// import * as SecureStore from 'expo-secure-store';
import * as OAuth2 from './OAuth2';
const mockedAxios = axios as jest.Mocked<typeof axios>;
jest.mock('axios');
describe('OAuth2', () => {
it('posts data to back end and handles the response correctly', async () => {
const data = {
data: {
accessJWT: 'token',
refreshJWT: 'refresh'
}
};
const SecureStore = require('expo-secure-store');
const mockGetItemAsync = jest.fn().mockResolvedValue({ refreshToken: 'refresh' });
SecureStore.getItemAsync = mockGetItemAsync;
mockedAxios.post.mockImplementationOnce(() => Promise.resolve(data));
return OAuth2.refreshAuth().then(res => expect(res).toEqual(data));
// expect(refreshAuth()).toHaveBeenCalledTimes(1);
// expect(mockGetItemAsync).toHaveBeenCalledWith('refresh');
});
});
现在它捕捉到错误,说它无法读取未定义的数据。
解决方案
推荐阅读
- sql-server - System.Data.SqlClient.SqlException:''''附近的语法不正确。'
- vb.net - vb.net 将数据从 BindingSource 保存到 db
- python-3.x - 如何更正值错误:未知标签类型“连续”
- python - 使用标准库从字符串中获取 MIME 类型
- gpflow - 如何让 GPFlow 在 Tensorflow 2 下运行?
- gml - Game Maker Studio 2 - 如何在控制同一个对象时赋予一个输入优先于另一个?
- flutter - 我升级了 Flutter(和 Dart),现在我无法让 WebApps 工作
- java - 在 Twilio 语音中,我如何拨打两个拨出电话并将两者连接在一起?
- rust - 使用 nom 以非零数字开头?
- typescript - 创建自定义对象的映射,我可以访问对象方法吗?(打字稿)