为什么我的测试失败,并且lodash方法中的console.log()语句没有记录日志

Why are my tests failing and console.log() statements within a lodash method not logging?

本文关键字:log console 语句 记录日志 失败 测试 我的 并且 方法 lodash 为什么      更新时间:2023-09-26

我有一些失败的测试,在各种lodash方法上都失败了,但在浏览器中工作得很好。在尝试调试时,我在回调参数内扔了一些console.log(),看看发生了什么,但它们没有出现在测试中。在浏览器中运行的相同代码既可以正常工作,又可以写入控制台。我怀疑中断的功能与缺少日志语句有关。

这是一个我将lodash作为服务提供的Angular应用。

应用

app.value('_', window._);
app.service('myService', function(_) {
  return {
    filterNulls: function(obj) {
      // This logs correctly everywhere
      console.log(obj);
      return _.omit(obj, function(val, key) {
        // This logs in browsers but not in the Jasmine/Karma environment
        console.log('test');
        return val === null;
      });
    }    
  };
});
测试

describe('myService', function() {
  beforeEach(function() {
    module(function($provide) {
      $provide.value('_', window._);
    });
  });
  it('should strip nulls', inject(function(myService) {
    // FAILS because null value is not removed
    expect(myService.filterNulls({ 
        key: 'key1', 
        someProp: 'bar', 
        someOtherProp: null 
      }))
      .toEqual({ 
        key: 'key1', 
        someProp: 'bar'
      });
  });
});

我不确定为什么当Karma运行时您的日志没有显示-当我测试您的代码时它们会为我显示。可能还有一个你我都不太清楚的问题。

我可以说你对_.omit的使用是不正确的。来自文档:

这个回调函数绑定到thisArg,并使用三个参数调用;(value, key, object).

同时,你的回调参数看起来像这样:

function(key, val) { .. }

这个小小的调整使你的测试通过了我:

function(val) { .. }

原来问题是一个不正确的lodash引用。karma.config文件引用的版本(lodash.underscore.js)与应用程序(lodash.compat.js)不同。协作开发不一致性的简单问题。