8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

为 JavaScript 字典分配动态值

BigBen 2月前

93 0

我需要将动态值分配给 JavaScript 字典以用于 echarts,但是在将动态值分配给字典时,它显示的行为与分配 s 相比有所不同......

我需要将动态值分配给 JavaScript 字典以用于 echarts,但是当将动态值分配给字典时,它显示的行为与分配静态值不同。

分配静态值时:

     response = {
            "stacks": {"5G_L2": [{"Open": "43"},{"Close": "24"}],
                       "5G_L3": [{"Open": "12"},{"Close": "2"}]
                      }
                  }; 

调试窗口显示如下:

enter image description here

而当动态分配值时,如下所示:

            var datastck=[];
            var serverdata = '{{ barCdata | tojson }}';
            resPbar = $.parseJSON(serverdata);

            $.each(resPbar, function (i, item) {
              var di={};
              di[item.Team]=[{"Open": item.Open},{"Close": item.Close}];
              datastck.push(di);
            });

            
          response = {
            "stacks": datastck
                  };

调试窗口如下:

enter image description here

它添加了一个额外的数组层。我需要有静态分配结构来支持 echarts,请有人提供建议?

提前致谢。

帖子版权声明 1、本帖标题:为 JavaScript 字典分配动态值
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由BigBen在本站《dictionary》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 控制台总是显示数组的索引 - 这是你的另一个问题吗?是的,数组只是对象……每个项目都有一个索引作为键

  • 如果您明确地将项目推送到数组中,那么当您得到一个数组作为结果时,您一定不会感到奇怪......您想要

  • 尝试这个:

    var serverdata = '{{ barCdata | tojson }}';
    resPbar = $.parseJSON(serverdata);
    
    var response = {
        "stacks": {}
    };
    
    $.each(resPbar, function (i, item) {
        response.stacks[item.Team].push({
            "Open": item.Open,
            "Close": item.Close
        });
    });
    
  • stacks[item.Team].push( 将不起作用,因为 stacks[item.Team] 不是一个数组(至少在该属性的初始集上),它应该(最有可能)是 stacks[item.Team] =(假设 item.Team 是唯一的,这在 OPs 代码中似乎是这样的)

  • 你说得对!response.stacks[item.Team] = [{ 应该可以正常工作,正如你所说

  • 我正在使用 bUnit 测试 Blazor 组件,但是在尝试模拟组件中的以下注入依赖项时遇到困难... [注入] public ILocalStorageService LocalStorage { ge...

    我正在使用 bUnit 测试 Blazor 组件,但是在尝试模拟组件中以下注入的依赖项时遇到了困难……

      [Inject]
      public ILocalStorageService LocalStorage { get; set; } = null!;
    

    我创建被测组件实例的基本代码是......

    TestComponentSender cut = RenderComponent<TestComponentSender>(ps => ps
        .Add(p => p.NotificationHelper, new TestNotificationHelper())
    ).Instance;
    

    我无法像使用 Add 那样使用该方法 NotificationHelper ,因为注入的是本地存储属性,而不是参数。

    我尝试在上面的代码之前添加以下行......

    Services.AddScoped<ILocalStorageService>();
    

    ...但是在运行测试时会出现异常......

    无法实例化服务类型“Blazored.LocalStorage.ILocalStorageService”的实现类型“Blazored.LocalStorage.ILocalStorageService”

    我尝试引用 NSubstitute Nuget 包,并在创建组件后添加以下行...

    cut.LocalStorage = Substitute.For<ILocalStorageService>();
    

    ...但这给出了一个不同的例外......

    无法为类型“InspiredGiving.Crm.Areas.General.Shared.TestComponentSender”上的属性“LocalStorage”提供值。没有类型为“Blazored.LocalStorage.ILocalStorageService”的注册服务。

    有人能告诉我如何模拟这种注入的依赖关系吗?

    更新 根据 Egil 的回答,我安装了 bUnit 测试包,并做了一些与 GitHub 页面上的代码类似的事情……

    TestComponentSender cut = RenderComponent<TestComponentSender>(ps => ps
      .Add(p => p.NotificationHelper, new TestNotificationHelper())
    ).Instance;
    cut.LocalStorage = this.AddBlazoredLocalStorage();
    

    然而,这却出现了例外……

    System.InvalidOperationException:无法为类型“InspiredGiving.Crm.Areas.General.Shared.TestComponentSender”上的属性“LocalStorage”提供值。没有类型为“Blazored.LocalStorage.ILocalStorageService”的注册服务

    我尝试使用罗伯特哈维在他的评论中展示的方法......

    Services.AddScoped<ILocalStorageService>(_ => this.AddBlazoredLocalStorage());
    
    

    ...但遇到了同样的异常。

  • 在 Vaughn Vernon 所著的《实施领域驱动设计》一书中,在值对象测试部分,作者讨论了如何使用浅拷贝而不是深拷贝来......

    在 Vaughn Vernon 的《实施领域驱动设计》一书中,在值对象测试部分,作者讨论了如何使用浅拷贝而不是深拷贝来测试对象的可变性。

    这是 BusinessPriority 的构造函数

    public final class BusinessPriority implements Serializable {
     private static final long serialVersionUID = 1L;
     private BusinessPriorityRatings ratings;
     public BusinessPriority(BusinessPriorityRatings aRatings) {
         super();
         this.setRatings(aRatings);
     }
     public BusinessPriority(BusinessPriority aBusinessPriority) {
         this(aBusinessPriority.ratings());
     }
    

    这是测试用例

     public void testCostPercentageCalculation() throws Exception {
         BusinessPriority businessPriority = new BusinessPriority(
             new BusinessPriorityRatings(2, 4, 1, 1));
         BusinessPriority businessPriorityCopy =
             new BusinessPriority(businessPriority);
     
        assertEquals(businessPriority, businessPriorityCopy);
     
        BusinessPriorityTotals totals = new BusinessPriorityTotals(53, 49, 53 + 49, 37, 33);
     
        float cost = businessPriority.costPercentage(totals);
        
        assertEquals(this.oneDecimal().format(cost), "2.7");
        assertEquals(businessPriority, businessPriorityCopy);
     }
    

    这是 equals 方法

    @Override
     public boolean equals(Object anObject) {
        boolean equalObjects = false;
        if (anObject != null && this.getClass() == anObject.getClass()) {
            BusinessPriority typedObject = (BusinessPriority) anObject;
            equalObjects =
            this.ratings().equals(typedObject.ratings());
        }
        return equalObjects;
     }
    

    This is the paragraph in the book where author talks about Shallow copy

    如我所见,浅复制在这种情况下是不够的,因为浅复制将使 businessPriority.rating() 和 businessPriorityCopy.rating() 引用同一个对象,因此无论该对象的某些属性是否发生更改,它们始终相等

    所以我是对的吗?如果是这样,为什么这本书在这种情况下讨论浅层复制?

    /////////////////////

  • 因为他不是在测试评级是否相等,而是在测试持有评级的价值对象。

    因为它们是值相等(而不是引用相等),将值对象视为 java 17 记录,测试表明两个不可变对象通过浅拷贝保持相等。

  • 嗨,Sylvain,你的评论确实让我对这里的图片有了一些了解。但我还有一些问题。首先,如果我理解正确的话,最后一个断言将起到确保值对象 businessPriority 不变性的作用(与第一个断言一起)。但是,如果 businessPriority 属性的值发生变化 - 违反了不变性,测试如何检测到它?你能举个例子来说明为什么最后一个断言是必要的吗?

  • 嗨,Khoa,实际上 businessPriority 也是不可变的,这是一个很好的做法,因此 businessPriority 的属性根本不能改变。查看完整范围的类:github.com/VaughnVernon/IDDD_Samples/blob/master/iddd_agilepm/… setter 是私有的

  • 我正在编写 Flutter 测试,尝试模拟一种计算 BMI 的方法。尽管使用 when(...).thenReturn(...) 返回未来值,但我还是遇到了以下错误:EXC...

    我正在编写 Flutter 测试,尝试模拟一种计算 BMI 的方法。尽管使用 when(...).thenReturn(...) 返回未来值,但我仍遇到以下错误:

    EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK The following _TypeError was thrown running a test: type 'Null' is not a subtype of type 'Future<String>'

    怎么运行的

    1. p2

      • The user opens the app and enters their weight and height in the provided text fields.
      • The user presses the "Calculate BMI" button.
    2. p3

      • The app sends a request to the backend API with the weight and height as parameters.
      • The app uses the Provider package to manage state and the ApiService to handle the HTTP request.
    3. p4

      • The Spring Boot application receives the request and processes the BMI calculation.
      • The result is sent back to the app as a response.
    4. p5

      • The app displays the BMI result and changes the text color based on the BMI category.

    这是我的代码的相关部分:

    widget_测试.dart

    // Define a mock class for ApiService using Mockito
    class MockApiService extends Mock implements ApiService {}
    void main() {
      testWidgets('BMI Calculator Test', (WidgetTester tester) async {
        final MockApiService mockApiService = MockApiService();
    
        // Mock response for calculateBMI method
        when(mockApiService.calculateBMI(88, 186)).thenReturn(Future.value('22.2'));
    
        await tester.pumpWidget(
          ChangeNotifierProvider(
            create: (context) => mockApiService,
            child: MaterialApp(
              home: BmiCalculatorApp(),
            ),
          ),
        );
    
        // Verify if 'Calculate BMI' button is found on the screen
        expect(find.text('Calculate BMI'), findsOneWidget);
    
        // Find the ElevatedButton widget with 'Calculate BMI' text and tap it
        await tester.tap(find.widgetWithText(ElevatedButton, 'Calculate BMI'));
        await tester.pump();
    
        // Wait for the async operation to complete
        await tester.pump(Duration(seconds: 1));
    
        // Verify if 'BMI result:' text is found exactly once on the screen
        expect(find.text('Your BMI is 22.2'), findsOneWidget);
      });
    }
    

    api_服务.dart

    import 'package:mockito/mockito.dart';
    import 'package:flutter_test/flutter_test.dart';
    
    // Define a service class
    class ApiService {
      Future<String> calculateBMI(int weight, int height) async {
        // Implementation that calculates BMI
        return ((weight / (height / 100 * height / 100)).toStringAsFixed(1));
      }
    }
    
    // Define a mock class
    class MockApiService extends Mock implements ApiService {}
    
    void main() {
      // Create an instance of the mock class
      final mockApiService = MockApiService();
    
      // Set up the mock to return a specific value
      when(mockApiService.calculateBMI(88, 186)).thenReturn(Future.value('22.2'));
    
      // Test case
      test('Calculate BMI', () async {
        final result = await mockApiService.calculateBMI(88, 186);
        expect(result, '22.2');
      });
    }
    

    主程序

    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'api_service.dart'; // Import the ApiService class
    
    void main() {
      runApp(
        // This is the entry point of my Flutter application.
        ChangeNotifierProvider( // This widget is used to provide a ChangeNotifier to its descendants. ChangeNotifierProvider: Listens for changes in the information and updates the app automatically.
          create: (context) => ApiService(baseUrl: 'http://localhost:8080'), // Create an instance of ApiService with a base URL.
          child: MaterialApp( // A widget that configures the MaterialApp.
            home: BmiCalculatorApp(), // Set BmiCalculatorApp as the home screen of the app.
          ),
        ),
      );
    }
    
    class BmiCalculatorApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold( // Scaffold widget provides a standard app layout structure.
          appBar: AppBar( // AppBar is the top bar of the app that typically contains the title and actions.
            title: Text('BMI Calculator'), // Title of the AppBar.
          ),
          body: BmiCalculator(), // The main content of the app is BmiCalculator widget.
        );
      }
    }
    
    class BmiCalculator extends StatefulWidget {
      @override
      _BmiCalculatorState createState() => _BmiCalculatorState();
    }
    
    class _BmiCalculatorState extends State<BmiCalculator> {
      final TextEditingController _weightController = TextEditingController(); // Controller to manage weight input.
      final TextEditingController _heightController = TextEditingController(); // Controller to manage height input.
      String _message = "Please enter your height and weight"; // Initial message displayed to the user.
      Color _messageColor = Colors.black; // Color of the message text.
    
      @override
      void initState() {
        super.initState(); // super.initState() This method call ensures that the initialization process of the parent class (State) is executed. The parent class State may have some essential setup that needs to be done for your widget to function correctly.
        // No need to initialize ApiService here anymore
      }
    
      void _calculateBMI() async {
        double weight = double.parse(_weightController.text); // Get weight value from TextField.
        double height = double.parse(_heightController.text); // Get height value from TextField.
    
        try {
          // Use Provider.of to get ApiService instance.
          final ApiService apiService = Provider.of<ApiService>(context, listen: false); // Get ApiService instance.
          String result = await apiService.calculateBMI(weight, height); // Call calculateBMI method from ApiService.
    
          // Extract the BMI value from the result string.
    
          double bmi = double.parse(result.split(' ').last);
    
          // Determine the color based on the BMI value.
          if (bmi < 18.5) {
            _messageColor = Colors.orange; // Underweight
          } else if (bmi < 25) {
            _messageColor = Colors.green; // Healthy Weight
          } else if (bmi < 30) {
            _messageColor = Colors.red; // Overweight
          } else {
            _messageColor = Colors.grey; // Obese
          }
    
          setState(() {
            _message = result; // Update _message with the result.
          });
        } catch (e) {
          setState(() {
            _message = 'Error: $e'; // If an error occurs, update _message with error message.
            _messageColor = Colors.black; // Set color to black for error message.
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Padding(
          padding: const EdgeInsets.all(16.0), // Padding around the entire Column widget.
          child: Column( // Column widget to arrange children widgets vertically.
            crossAxisAlignment: CrossAxisAlignment.stretch, // Stretch widgets horizontally.
            children: <Widget>[
              TextField( // TextField widget for weight input.
                controller: _weightController, // Controller to manage text input.
                decoration: InputDecoration( // Decoration for TextField.
                  labelText: 'Weight (kg)', // Label text for TextField.
                ),
                keyboardType: TextInputType.number, // Allow numeric input.
              ),
              TextField( // TextField widget for height input.
                controller: _heightController, // Controller to manage text input.
                decoration: InputDecoration( // Decoration for TextField.
                  labelText: 'Height (cm)', // Label text for TextField.
                ),
                keyboardType: TextInputType.number, // Allow numeric input.
              ),
              SizedBox(height: 20), // Empty space with a height of 20 pixels.
              ElevatedButton( // ElevatedButton widget for BMI calculation.
                onPressed: _calculateBMI, // Function to execute when button is pressed.
                child: Text('Calculate BMI'), // Text displayed on the button.
              ),
              SizedBox(height: 20), // Empty space with a height of 20 pixels.
              Text( // Text widget to display BMI calculation result or error message.
                _message, // Text to display.
                textAlign: TextAlign.center, // Center-align the text.
                style: TextStyle(fontSize: 24, color: _messageColor), // Font size and color of the text.
              ),
            ],
          ),
        );
      }
    }
    

    pubspec.yaml

    remove all comments: 
    name: bmi_calculator
    description: "A new Flutter project."
    
    
    version: 1.0.0+1
    
    environment:
      sdk: '>=3.4.3 <4.0.0'
    
    dependencies:
      flutter:
        sdk: flutter
    
      http: ^0.13.3
      provider: ^5.0.0
    
      cupertino_icons: ^1.0.6
    
    dev_dependencies:
      flutter_test:
        sdk: flutter
    
      mockito: ^5.0.7
      
      flutter_lints: ^3.0.0
    
      uses-material-design: true
    

    我尝试过的:

    1. p11

      when(mockApiService.calculateBMI(88, 186)).thenAnswer((_) async => '22.2');
    2. p12

      when(mockApiService.calculateBMI(any, any)).thenReturn(Future<String>.value('22.2'));
    3. p13

      when(mockApiService.calculateBMI(88, 186)).thenAnswer((invocation) async {  final int weight = invocation.positionalArguments[0];  final int height = invocation.positionalArguments[1];  return '22.2';});

    问题:

    Despite these attempts, I am still encountering the type 'Null' is not a subtype of type 'Future<String>' error.My main.dart 
    

    问题:

    How can I resolve this TypeError and correctly mock the calculateBMI method to return the expected future value?
    

    我的 Flutter 程序运行完美,但似乎无法通过 widget_test.dart

  • D yh 2月前 0 只看Ta
    引用 13

    这看起来像是 Mockito 和 Dart 声音空安全的问题。

    正如 NULL_SAFETY_README 所述,由于参数匹配和返回类型的原因,以下代码在健全的空安全下是非法的。有关详细信息,请参阅链接。

    class HttpServer {
      Uri start(int port)  {
        // ...
      }
    }
    
    class MockHttpServer extends Mock implements HttpServer {}
    
    var server = MockHttpServer();
    var uri = Uri.parse('http://localhost:8080');
    when(server.start(any)).thenReturn(uri);
    

    你的嘲笑也同样如此 ApiServer

    自述文件提供了两种解决方案:代码生成或使用反射手动实现模拟。在后一种情况下,模拟将如下所示

    class MockHttpServer extends Mock implements HttpServer {
      @override
      void start(int? port) =>
          super.noSuchMethod(Invocation.method(#start, [port]));
    }
    

    从那里,您可以 when() 像以前一样 capture()

    对于更复杂的模拟,代码生成方法是更好的选择。

  • 通过覆盖 MockApiService 类中的 calculateBMI 效果很好。

  • class MockApiService extends Mock implements ApiService {
      @override
      Future<String> calculateBMI(int weight, int height) {
        return super.noSuchMethod(
          Invocation.method(#calculateBMI, [weight, height]),
          returnValue: Future.value('22.2'), // This is a Future<String>
          returnValueForMissingStub: Future.value('22.2'), // Default return value
        );
      }
    }
    
  • 我有 7 种简单产品,分为 2 个分组产品。在一个分组产品中,我允许任何客户无限制购买。在另一个分组产品中,我仅允许在以下情况下添加到购物车:

    我有 7 种简单产品,分为 2 个分组产品。在一个分组产品中,我允许任何客户不受任何限制地购买。在另一个分组产品中,我仅允许客户将特定产品添加到购物车中。

    如何获取分组产品 ID 来添加条件?

    到目前为止,我的代码片段适用于两种分组产品:

    add_filter( 'woocommerce_add_to_cart_validation', 'check_variable_product_in_cart', 10, 3 );
    function check_variable_product_in_cart( $passed, $product_id, $quantity ) {
        
        // Check if the product being added is one of the specific products
        $specific_products = array( 8541, 8542, 8543, 8544, 8545, 8546, 15985 ); // Replace with your specific product IDs
        if ( in_array( $product_id, $specific_products ) ) {
    
            // Check if the variable product is in the cart
            $variable_product_id = 8475; // Replace with your variable product ID
            $found = false;
            foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( $cart_item['product_id'] == $variable_product_id ) {
                    $found = true;
                    break;
                }
            }
    
            // If variable product is not in cart, prevent addition of specific products
            if ( ! $found ) {
                $passed = false;
                $product_name = get_the_title( $product_id );
                wc_add_notice( sprintf( __( 'sorry, you must buy product 8475 first', 'your-theme' ), $product_name ), 'error' );
            }
        }
    
        return $passed;
    }
    
  • 假设产品 ID 8475 是购物车中必需的产品(而不是目标分组产品的一部分)。

    请尝试以下操作(在下面定义您的目标分组产品 ID):

    add_filter( 'woocommerce_add_to_cart_validation', 'check_variable_product_in_cart', 10, 3 );
    function check_variable_product_in_cart( $passed, $product_id, $quantity ) {
        $targeted_grouped_product_id = 36; // Define here the related grouped product ID
        $required_product_id_in_cart = 8475; // Replace with your specific product ID (in cart)
    
        // Check for the gouped product ID
        if ( intval($_POST['add-to-cart']) === $targeted_grouped_product_id ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( $cart_item['product_id'] == $required_product_id_in_cart ) {
                    return true;
                }
            }
            $product = wc_get_product($required_product_id_in_cart);
            wc_clear_notices();
            wc_add_notice( sprintf( __( 'Sorry, the product %s must be added to cart first.', 'woocommerce' ), 
                '<a href="'.$product->get_permalink().'"><strong>"'.$product->get_name().'"</strong></a>' 
            ), 'error' );
            return false;
        }
        return $passed;
    }
    

    代码放在子主题(或插件)的 functions.php 文件中。已测试并有效。

    enter image description here

  • 我正在尝试对 react-native 项目进行一些测试,但是 jest 遇到了这个错误,我不知道为什么:FAIL __tests__/(tabs)/weather.test.tsx 测试套件无法运行 Jest

    我正在尝试对 react-native 项目进行一些测试,但是 jest 遇到了这个错误,我不知道原因:

     FAIL  __tests__/(tabs)/weather.test.tsx
       Test suite failed to run
    
        Jest encountered an unexpected token
    
        Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
    
        Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
    
        By default "node_modules" folder is ignored by transformers.
    
        Here's what you can do:
         • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
         • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
         • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
         • If you need a custom transformation specify a "transform" option in your config.
         • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
        You'll find more details and examples of these config options in the docs:
        https://jestjs.io/docs/configuration
        For information about custom transformations, see:
        https://jestjs.io/docs/code-transformation
    
        Details:
    
        /Users/j/Downloads/tdd-expo/node_modules/react-redux/dist/react-redux.legacy-esm.js:34
        import * as React2 from "react";
        ^^^^^^
    
        SyntaxError: Cannot use import statement outside a module
    
          3 | import { render } from "@testing-library/react-native";
          4 | import React, { PropsWithChildren } from "react";
        > 5 | import { Provider } from "react-redux";
            | ^
          6 |
          7 | const AllTheProviders = ({ children }: PropsWithChildren) => {
          8 |   return (
    
          at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
          at Object.require (test-utils.tsx:5:1)
          at Object.require (/Users/j/Downloads/tdd-expo/__tests__/(tabs)../../../../weather.test.tsx:2:1)
    

    这似乎是失败的地方:

        Details:
    
        /Users/j/Downloads/tdd-expo/node_modules/react-redux/dist/react-redux.legacy-esm.js:34
        import * as React2 from "react";
        ^^^^^^
    

    因此,无法将其导入文件 test-utils.tsx

    // test-utils.tsx
    import { DarkTheme, ThemeProvider } from "@react-navigation/native";
    import "@testing-library/jest-native/extend-expect";
    import { render } from "@testing-library/react-native";
    import React, { PropsWithChildren } from "react";
    import { Provider } from "react-redux"; // Is failing to import here
    
    const AllTheProviders = ({ children }: PropsWithChildren) => {
      return (
        <Provider store={{} as any}>
          <ThemeProvider value={DarkTheme}>{children}</ThemeProvider>
        </Provider>
      );
    };
    
    const customRender = (ui: React.ReactElement, options: any) =>
      render(ui, { wrapper: AllTheProviders, ...options });
    
    // re-export everything
    export * from "@testing-library/react-native";
    
    // override render method
    export { customRender as render };
    

    以下是 jest 的配置:

    // package.json
    {
    // ...
      "jest": {
        "preset": "jest-expo",
        "transformIgnorePatterns": [
          "node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg)"
        ],
        "collectCoverage": true
      },
    
    // ...
    }
    

    我遵循了以下指南: https://docs.expo.dev/develop/unit-testing/

    并尝试了这个自定义渲染设置: https://testing-library.com/docs/react-testing-library/setup/#custom-render

    我期望 jest 能够成功运行,但实际上它导致了“import”错误。

    知道发生了什么吗?提前致谢

  • 引用 19

    @Steve 我还没有解决这个问题。如果我找到解决方案,我会告诉你的。如果你找到了,也请告诉我。

  • 我编写了一个函数来获取验证准确性def 评估(loader,model,device):model.eval()model.to(device)correct = 0 total = len(loader.dataset)for data in loader...

    我编写了一个函数来获取验证准确率

    def evaluation(loader, model, device):
        model.eval()
        model.to(device)
        correct = 0
        total = len(loader.dataset)
        for data in loader:
            with torch.no_grad():
                inputs, labels = data[0].to(device), data[1].to(device)
                pred = model(inputs)
                pred = pred.argmax(dim=1)
            correct += pred.eq(labels).sum().item()
     
        acc = correct / total
        return acc
    

    但当我测试它时,我发现 for 循环被跳过了。为什么?我的加载器和数据集在这张图中,请 在此处输入图片说明

    数据加载器代码:

       data_list = list(range(0, len(dataset)))
        val_list = random.sample(data_list, int(len(dataset) * val_split))
        trainset = [dataset[i] for i in data_list if i not in val_list]
        valset = [dataset[i] for i in data_list if i in val_list]
    
        # Weighed Sampling
        if weighted_sampling:
            label_count = Counter([int(data[1]) for data in dataset])
            weights = [100 / label_count[int(data[1])] for data in trainset]
            sampler = WeightedRandomSampler(weights, num_samples=len(trainset), replacement=True)
            train_loader = DataLoader(trainset, batch_size=batch_size, sampler=sampler, drop_last=True)
        else:
            train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=False, drop_last=True)
    
        val_loader = DataLoader(valset, batch_size=batch_size, shuffle=True, drop_last=True)
    

    我尝试检查我的数据集和数据加载器,但没有发现任何错误。我期待原因,谢谢

返回
作者最近主题: