【问题标题】:How to simulate calling a utility function using jest?如何使用 jest 模拟调用实用程序函数?
【发布时间】:2019-04-15 00:46:10
【问题描述】:

我正在测试一个返回整数的实用函数,我正在尝试模拟调用它,但即使经过数小时的谷歌搜索,我也找不到正确的方法。

我也试过spyOn(),但似乎没有用。

身份验证.js

export function auth(username) {
  AsyncStorage.getItem('@app:id').then((id) => {
    if (id === username) {
      return 1;
    }
    return 0;
  });
}

Authentication.test.js

import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer'; // Note: test renderer must be required after react-native.
import mockAxios from 'axios';
import mockAsyncStorage from '@react-native-community/async-storage';
import auth from '../App/Utils/Authorization';

test('should check whether the user whose username is entered as a paramter is the same as the user logged in the application', () => {
  auth = jest.fn();
  expect(auth).toHaveReturned();
  expect(mockAsyncStorage.getItem).toHaveBeenCalledTimes(1);
  expect(mockAsyncStorage.multiRemove).toHaveBeenCalledWith('@app:id');
});

我希望模拟调用 auth() 并成功测试,但每当运行 yarn test 时,我都会收到错误 "auth" is read-only 作为输出。

【问题讨论】:

    标签: react-native jestjs


    【解决方案1】:

    您正在重新分配导入的成员 auth,而不是以应有的方式使用 jest.fn()。调用 jest mock 函数将返回 undefined,而使用 mockFn.mockImplementation(fn) 您可以将函数绑定到 mock 并测试它是否被调用或返回一些预期值。

    import auth from '../App/Utils/Authorization';
    
    test('Test auth', () => {
        const mockAuth = jest.fn().mockImplementation(auth);
        mockAuth();
        expect(mockAuth).toHaveBeenCalled();
    }
    

    您可以验证您的函数检查mockFn.mock.results 的输出,它存储了对您的调用函数进行的每次调用的结果。

    test('when user is provided', () => {
        mockAuth({ user: {id: 'test', name: 'test'} });
        expect(mockAuth).toHaveBeenCalled();
    
        const result = mockAuth.mock.results[0].value;
        expect(result).toBe(1);
    });
    

    【讨论】:

    • 这解决了大部分问题,但是如何在模拟函数模拟实现中使用模拟函数呢?具体来说,如何在mockAuth 中使用模拟的 AsyncStorage 函数?
    • 抱歉,我没有看到您的 auth 函数正在返回一个承诺。在这种情况下,jest documentation 中有许多异步示例。 expect(result).resolves.toEqual(1) 应该可以工作
    猜你喜欢
    • 2019-10-31
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2019-07-22
    • 2021-03-28
    • 1970-01-01
    • 2021-08-11
    • 2021-09-22
    相关资源
    最近更新 更多