小编Jon*_*ins的帖子

如何在模块取消模拟时在Jest中模拟导入的命名函数

我有以下模块我试图在Jest中测试:

// myModule.js

export function otherFn() {
  console.log('do something');
}

export function testFn() {
  otherFn();

  // do other things
}
Run Code Online (Sandbox Code Playgroud)

如上图所示,这部分出口命名的功能和重要的testFn用途otherFn.

在Jest中我正在编写单元测试时testFn,我想模拟该otherFn函数,因为我不希望错误otherFn影响我的单元测试testFn.我的问题是我不确定最好的方法:

// myModule.test.js
jest.unmock('myModule');

import { testFn, otherFn } from 'myModule';

describe('test category', () => {
  it('tests something about testFn', () => {
    // I want to mock "otherFn" here but can't reassign
    // a.k.a. can't do otherFn = jest.fn()
  });
});
Run Code Online (Sandbox Code Playgroud)

任何帮助/见解表示赞赏.

unit-testing ecmascript-6 jestjs

61
推荐指数
6
解决办法
4万
查看次数

jQuery $ .post处理JSON响应

我无法弄清楚如何从jQuery $ .post()请求中正确读取我的JSON响应.

在下面的jQuery代码中,我根据我用作关键字的相应"color_entry_id"填充DOM中元素的关联数组字符串:

var image_links = {};
$(this).find('input[name="color_id"]').each(function() {
    var color_entry_id = $(this).val();
    var image_link = $(this).parent().find('input[name="edit_image"].' + color_entry_id).val();
    image_links[color_entry_id] = image_link;
});
Run Code Online (Sandbox Code Playgroud)

然后我发出POST请求,发送我的"image_links"数组:

$.post(
    "test.php",
    { id: product_id, "images[]": jQuery.makeArray(image_links) },
    function(data) {
        var response = jQuery.parseJSON(data);
        $.each(response.images, function(index, item) {
             alert(item);
        });
    }
);
Run Code Online (Sandbox Code Playgroud)

另外,如上所示,我尝试循环遍历响应数组并输出每个项目,我想成为一个字符串,但我只得到"[object Object]"作为警告值.我不知道如何让它显示我想要显示的字符串!

这是test.php的PHP代码:

<?php
    $product_id = $_POST['id'];
    $images = $_POST['images'];

    $response = array();
    $response['id'] = $product_id;
    $response['images'] = $images;

    echo json_encode($response);
?>
Run Code Online (Sandbox Code Playgroud)

以下是DOM的相关部分:

<input type='hidden' value='{{ color_entry_id }}' name='color_id' />
<p><img src='{{ color_img_link …
Run Code Online (Sandbox Code Playgroud)

php jquery json

15
推荐指数
2
解决办法
6万
查看次数

Apache POI宽度计算

我通过计算columnWidth和我计算的行高来获得我想要的确切大小时遇到​​问题,因为我不懂文档.

就columnWidth而言,我使用的是代码行,sheet.setColumnWidth(int columnIndex, int width);但我不明白如何正确计算宽度.我明白了:

width = Truncate([{Number of Visible Characters} * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
Run Code Online (Sandbox Code Playgroud)

所以我有一个确切的Excel工作表示例我要创建的内容,当我突出显示一列并选择列宽时,它会告诉我它9.67 (94 pixels).那么这是什么意思?如何将其插入到我的等式中以获得我想要的宽度值?

我遇到的另一个问题是我正在使用我在别处找到的代码(甚至在SO上)来动态计算行高.但我的问题是我不明白mergedCellWidth下面的代码中应该是什么内容nextPos = measurer.nextOffset(mergedCellWidth).我似乎无法正确地获得这个值,并且它弄乱了它认为应该有多少行,因此我的行高度不对.

java.awt.Font currFont = new java.awt.Font("Calibri", 0, 11);
AttributedString attrStr = new AttributedString(record.getDescription());
attrStr.addAttribute(TextAttribute.FONT, currFont);

// Use LineBreakMeasurer to count number of lines needed for the text
FontRenderContext frc = new FontRenderContext(null, true, true);
LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(), frc);
int nextPos = 0;
int lineCnt …
Run Code Online (Sandbox Code Playgroud)

apache-poi

7
推荐指数
1
解决办法
1万
查看次数

Calendar.get(Calendar.HOUR)问题

我正在尝试在我的应用程序最后更新时显示在TextView中(例如,"上次更新时间为12:13).我正在尝试使用Calendar实例,我认为我理解正确,但我似乎遇到了麻烦.我知道获取一个实例我使用Calendar.getInstance()方法.然后得到我使用Calendar.get(Calendar.HOUR)和Calendar.get(Calendar.MINUTE)的小时和分钟.我的分钟字段正确返回但是日历.HOUR小时24小时回来,我想要一个12小时的时钟.我觉得HOUR_OF_DAY是24小时制.我哪里错了?

这是我正在使用的代码:

Calendar rightNow = Calendar.getInstance();
mTv.setText("Refreshed! Last updated " + 
           rightNow.get(Calendar.HOUR) + ":" + 
           rightNow.get(Calendar.MINUTE) + ".");
Run Code Online (Sandbox Code Playgroud)

mTv是我正在更新的TextView.谢谢你的帮助.

此外,如果我能说"最近更新5分钟前",那将是理想的选择.而不是"最后更新时间为下午12:13".但是我不确定每分钟都有这种更新的最佳方法,而不会耗尽资源或电池......?

android calendar android-calendar

6
推荐指数
2
解决办法
2万
查看次数

ArrayList的有效onDraw

我有一个自定义视图,在其上绘制了一个ArrayList of Coordinates(这是一个仅包含x和y位置的自定义类)。随着越来越多的坐标添加到ArrayList中,绘图明显变慢了。我想知道是否有一种更有效的方式绘制此ArrayList,或者是否可以仅添加一个已添加的坐标(因为ArrayList仅在两次调用之间更改了一个坐标以使之无效)。

以下是相关的代码段:

public class CustomDraw extends View {
// member variables

public void updateLine() {
    // grab new coordinates for each measure

    if(measure1.isEmpty()) {
        measure1.add(new Coordinate(0, 0));
    } else {
        Coordinate last_coord = measure1.get(measure1.size() - 1);

        // calculations for south, north, east, and west

        if(south && east) {
            measure1.add(new Coordinate(last_coord.x + 3, last_coord.y + 3));
        } else if(south && west) {
            measure1.add(new Coordinate(last_coord.x - 3, last_coord.y + 3));
        } else if(north && east) {
            measure1.add(new Coordinate(last_coord.x + 3, …
Run Code Online (Sandbox Code Playgroud)

android arraylist android-custom-view android-canvas

5
推荐指数
1
解决办法
983
查看次数

jQuery FormData POST - 用于文件上传

我正在尝试使用jQuery提交服务器端处理的完整表单.表单包含各种字段,包括文件上载选项.我正在尝试使用FormData来执行此操作,因为我不关心目前不支持它的浏览器.

我有以下(简化的)jQuery代码:

$("#create_event_form").submit(function(event) {
    event.preventDefault();

    var formData = new FormData($(this));

    $.post(
        "create_entity.php",
        { formData: formData },
        function(data) {
            var response = jQuery.parseJSON(data);
            if(response.code == "success") {
                alert("Success!");
            } else if(response.code == "failure") {
                alert(response.err);
            }
        }
    );
});
Run Code Online (Sandbox Code Playgroud)

我的服务器端如下所示:

<?php
require_once('includes/database.php');


$dbh = db_connect();

$response = array();
if($_SERVER['REQUEST_METHOD'] == "POST") {
    // do some other stuff...       

    // upload entity picture and update database
    $url = $_FILES['entity_pic']['name'];
    if($url != "") {
        if($type == "user") {
            $pic_loc = "images/profiles/";
        } else if($type …
Run Code Online (Sandbox Code Playgroud)

jquery html5 file-upload asyncfileupload

5
推荐指数
1
解决办法
2万
查看次数

在Bootstrap 3上有问题SlideDown()隐藏元素

能否请您看看这个演示,让我知道为什么change()功能无法slideDown()一个hidden元素在引导3?

这是我的代码

$(function() {
    $('input:radio').change(function() {
        if($(this).val()== 'Dog') {
            $('#hidden-list-1').slideDown();
        }
        if($(this).val()== 'Bird'){
            $('#hidden-list-2').slideDown();  
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

javascript jquery twitter-bootstrap twitter-bootstrap-3

5
推荐指数
1
解决办法
1529
查看次数

写入PHP输出缓冲区,然后从缓冲区下载CSV

我需要将一个CSV文件写入PHP输出缓冲区,然后在写完文件后将该文件下载到客户端的计算机上.(我想把它写在服务器上并下载它正在工作,但事实证明我不会在生产服务器上有写访问权限).

我有以下PHP脚本:

$basic_info = fopen("php://output", 'w');
$basic_header = array(HEADER_ITEMS_IN_HERE);

@fputcsv($basic_info, $basic_header);

while($user_row = $get_users_stmt->fetch(PDO::FETCH_ASSOC)) {
    @fputcsv($basic_info, $user_row);
}

@fclose($basic_info);

header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=test.csv');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("php://output"));
ob_clean();
flush();
readfile("php://output");
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做.CSV文件下载但不显示任何内容.我认为它与我的ob_clean()和flush()命令的顺序有关,但我不确定订购这些东西的最佳方法是什么.

任何帮助表示赞赏.

php csv

4
推荐指数
1
解决办法
2万
查看次数

Grunt连接没有以错误"root path必须是一个字符串"开头

我正在尝试设置我的Gruntfile以使用grunt connect npm模块.尝试使用该命令启动我的服务器时遇到问题grunt clean server.它出错了:

Warning: root path must be a string Use --force to continue.
Run Code Online (Sandbox Code Playgroud)

我真的不确定我搞砸了什么配置,可以用另一双眼睛.这是我的Gruntfile:

/* global module, conf */
var modRewrite = require('connect-modrewrite');
var mountFolder = function(connect, dir) {
    return connect.static(require('path').resolve(dir));
};
module.exports = function(grunt) {

    grunt.initConfig({
        copy: {
            base: {
                files: [
                    {src: "index.html", dest: "BUILD/index.html"},
                    {expand: true, src: "app/**", dest: "BUILD/"},
                    {expand: true, src: "assets/**", dest: "BUILD/"}
                ]
            }
        },

        connect: {
            proxies: [
                {
                    context: "/wwff",
                    host:  "localhost",
                    port: "8080"
                }
            ], …
Run Code Online (Sandbox Code Playgroud)

node.js gruntjs grunt-contrib-connect

4
推荐指数
1
解决办法
2675
查看次数

根据 TypeScript 中对象的数组参数动态生成返回类型

我正在尝试定义一个 TypeScript 定义,如下所示:

interface Config {
    fieldName: string
}
function foo<T extends Config>(arr: T[]): Record<T['fieldName'], undefined>
function foo(arr: Config[]): Record<string, undefined> {
  const obj = {}
  _.forEach(arr, entry => {
    obj[entry.fieldName] = undefined
  })

  return obj
}

const result = foo([{fieldName: 'bar'}])
result.baz // This should error since the array argument did not contain an object with a fieldName of "baz".
Run Code Online (Sandbox Code Playgroud)

上面的代码受到了 基于 TypeScript 中的参数动态生成返回类型的启发,这几乎正是我想要做的,除了我的参数是对象数组而不是字符串数组。

问题是 的类型result是Record<string, undefined>我想要的类型Record<'bar', undefined>。我很确定我的返回定义Record<T['fieldName'], undefined>不正确(因为T …

typescript typescript-typings

4
推荐指数
1
解决办法
1975
查看次数