如何在反应和反应测试库中模拟事件处理函数

时间:2021-01-22 05:38:19

标签: reactjs jestjs

我想知道如何在 react 和 react 测试库中模拟事件处理函数。

例如,在以下源代码中,当单击按钮时,会触发函数 <?php /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * ABOUT THIS PHP SAMPLE: This sample is part of the SDK for PHP Developer Guide topic at * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-examples-creating-buckets.html * */ // snippet-start:[s3.php.list_buckets.complete] // snippet-start:[s3.php.list_buckets.import] require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException; // snippet-end:[s3.php.list_buckets.import] /** * List your Amazon S3 buckets. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ //Create a S3Client // snippet-start:[s3.php.list_buckets.main] define('AWS_KEY', '*****'); define('AWS_SECRET_KEY', '***************'); // Instantiate the S3 class and point it at the desired host $s3Client = S3Client::factory(array('credentials' => [ 'key' => AWS_KEY, 'secret' => AWS_SECRET_KEY ],'region' => 'us-east-1','version' => 'latest')); //Listing all S3 Bucket $buckets = $s3Client->listBuckets(); foreach ($buckets['Buckets'] as $bucket) { echo $bucket['Name'] . "\n"; }

handleClick

我想知道

  • 如何在 React 测试库和 jest 中创建模拟函数。
  • 如何在测试用例中将模拟函数设置到 dom 事件处理程序中。

2 个答案:

答案 0 :(得分:0)

对您的实用程序文件执行 import * as,然后您可以模拟其中的各个功能以进行测试。

import * as utils from "./PageTransitionUtil";

jest.mock("./PageTransitionUtil");

utils.goToSecondPage = jest.fn();

从这里开始,goToSecondPage 是一个模拟函数,您可以对其进行断言,即 expect(utils.goToSecondPage).toHaveBeenCalled()

答案 1 :(得分:0)

正如我在评论中所说,更喜欢模拟外部 api 和函数,这里有一种方法向您展示如何使用 jest.mock 工厂函数进行模拟。

jest.mock("./PageTransitionUtil", () => ({
  goToSecondPage: jest.fn(),
  //Add other methods you want to mock here
}));

你可以在官方jest文档中阅读更多相关信息