首页 > 解决方案 > 使用 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');
  });
});

现在它捕捉到错误,说它无法读取未定义的数据。

标签: javascriptreactjsreact-nativeunit-testingjestjs

解决方案


推荐阅读