使用 Jest 模拟值的问题

Issue with mocking values using Jest

我正在尝试在已使用酶和茉莉花设置的现有项目中设置 Jest。 我已经安装了 jest 包并设置了初始配置,但现在我 运行 遇到了一个问题,即没有正确提供模拟数据。当 运行 没有开玩笑时,相同的测试在项目中工作正常。

这是失败测试的控制台输出:

macbook-pro:$ ./node_modules/.bin/jest 
 FAIL  spec/cookieSpec.js
  Cookie Parser should
    ✓ return an empty string (17 ms)
    ✓ return null (2 ms)
    ✕ return the session value (2 ms)
    ✕ be able to handle multiple cookies (2 ms)
    ✕ be able to handle badly formatted cookies (1 ms)

  ● Cookie Parser should › return the session value

    expect(received).toMatch(expected)

    Expected substring: "4332432423"
    Received string:    ""

      24 |     const result = getSessionId();
      25 |     expect(result).not.toBe(null);
    > 26 |     expect(result).toMatch('4332432423');
         |                    ^
      27 |     done();
      28 |   });
      29 | 

      at Object.<anonymous> (spec/cookieSpec.js:26:20)

package.json 中的 Jest 配置:

"jest": {
    "verbose": true,
    "moduleNameMapper": {
      "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "spec/mocks/*.js",
      "\.(css|less)$": "spec/mocks/*.js"
    },
    "moduleDirectories": [
      "node_modules"
    ],
    "setupFilesAfterEnv": [
      "jest-enzyme"
    ],
    "transform": {
      "^.+\.jsx?$": "babel-jest"
    },
    "testEnvironment": "enzyme",
    "testEnvironmentOptions": {
      "enzymeAdapter": "react16"
    },
    "testMatch": [
      "**/spec/*Spec.js?(x)"
    ]
  },

来自测试文件的代码cookieSpec.js

import {getSessionId} from 'Js/cookieReader.js';

describe('Cookie Parser should', function() {
  let _document = {cookie: ''};
  beforeEach(function() {
    global.document = _document;
  });

  it('return an empty string', function(done) {
    const result = getSessionId();
    expect(result).toBe('');
    done();
  });

  it('return null', function(done) {
    _document.cookie='ga=32213123';
    const result = getSessionId();
    expect(result).toBe('');
    done();
  });

  it('return the session value', function(done) {
    _document.cookie = 'connect.sid=4332432423';
    const result = getSessionId();
    expect(result).not.toBe(null);
    expect(result).toMatch('4332432423');
    done();
  });

  it('be able to handle multiple cookies', function(done) {
    _document.cookie='ga=32213123;connect.sid=4332432423';
    const result = getSessionId();
    expect(result).toBe('4332432423');
    done();
  });

  it('be able to handle badly formatted cookies', function(done) {
    _document.cookie=' ga=32213123;connect.sid= 4332432423';
    const result = getSessionId();
    expect(result).toBe('4332432423');
    done();
  });
});

事实证明,有设置代码建立了 cookie 模拟,运行 用于 jasmine 而不是用于 jest。一旦为开玩笑建立了模拟,测试就通过了。