首页 > 解决方案 > For循环纯函数玩笑测试使用expect ...无法读取属性

问题描述

我正在尝试使用 for 循环制作一个纯函数,在终端中通过一个 jest 测试/npm 测试...我收到一个错误,它无法读取 toBe 的属性...

我的功能:

const syntax = {
   for1: (a,b) => {
      for(let a=1; a<10; a++){
         for(let b=1; b<10; b++){
             return a+b;
         }
      }
   }
}

我的 Test.js 文件:我希望它测试 1+2 不等于 0 使该测试通过函数

test('FORLOOP', () => {
    expect(syntax.for1(1,2).not.toBe(0));
});

终端中的类型错误:

TypeError: Cannot read property 'toBe' of undefined
      45 | test('FORLOOP', () => {
    > 46 |     expect(syntax.for1(1+3).not.toBe(0));
         |            ^
      47 | });

变化:

测试文件:(固定括号)

test('FORLOOP', () => {
    expect(syntax.for1(1,2).not.toBe(0));
});
    TypeError: _syntax.default.for1 is not a function

      55 | 
      56 | test('FORLOOP', () => {
    > 57 |     expect(syntax.for1(1+3)).not.toBe(0);
         |                   ^
      58 | });

标签: for-looptestingjestjspure-function

解决方案


括号在错误的位置。它应该是:

expect(syntax.for1(1+3)).not.toBe(0);

不是

expect(syntax.for1(1+3).not.toBe(0));

.not需要在 的结果上调用,而expect(...)不是在 的结果上调用syntax.for1(1+3)


推荐阅读