首页 > 解决方案 > 我怎样才能开玩笑地测试这个功能?

问题描述

我目前对该文件的分支覆盖率为 0%,我不确定如何测试它。

import { RouterState } from '../router';
import { AuthStore } from '../auth';

export const DEFAULT_ROUTE = '/account';
export const HOME_ROUTE = '/';
export const NOT_FOUND_ROUTE = 'not-found';

export const checkForUserSignedIn = () => {
  const authDataStore = new AuthStore();
  if (authDataStore.isAuthenticated) {
    return Promise.resolve();
  } else {
    return Promise.reject(new RouterState(HOME_ROUTE));
  }
};

标签: reactjsunit-testingjestjs

解决方案


为此,您可能需要提供AuthStore.

模拟是测试中的一个概念,基本上意味着您“为某些东西提供替代实现”,您的应用程序代码在执行单元测试期间使用它。

jest 框架提供了模拟功能 - 在您的情况下,模块模拟是相关的。

我在下面提供了一个粗略的示例来说明您的代码上下文中的概念,并且开玩笑。您需要为 , 提供一个模拟(或多个模拟)以供AuthStore您的测试使用,以允许您验证您的应用程序逻辑(即checkForUserSignedIn())在不同情况下(即何时isAuthenticated为真、何时为假等)的行为是否符合预期):

import * as User from 'YourUserModule' // ie, where checkForUserSignedIn is defined

// Tell jest you want to mock this module (assuming test located in same path as implementation)
// This module is where AuthStore is defined, which is the particular thing we're interested in mocking
jest.mock('../auth'); 

// Define a mock implementation of '../auth' for use in test
require('../auth')
.mockImplementation(() => {

    // An example of a mocked auth store class. This mocknever returns true for
    // isAuthenticated. We can use this mock to verify the behaviour of the
    // 'reject' code path
    class MockAuthStore {
        get isAuthenticated() {
            return false;
        }
    }

    // Return the mock class, to "replace" the existing implementation with this mock when running the test
    return {
        AuthStore : MockAuthStore
    }
})

// Now define your test
it('should reject when user is not authenticated', async () => {

    // An example of how you can verify that checkForUserSignedIn rejects when 
    // new AuthStore().isAuthenticated returns false
    await expect(User.checkForUserSignedIn()).rejects.toBeDefined();
});

推荐阅读