我有一段我一直在努力测试的代码。这是一个承诺,并且在这个承诺内还有另一个异步功能。例如:
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');
});
});
现在它捕获到错误,表示它无法读取未定义的数据。