为什么Jest在我的异步节点代码中报告这些行未包含在测试中?

时间:2018-07-25 20:12:10

标签: node.js asynchronous testing code-coverage jestjs

Jest报告了3条未涵盖的行,尽管据我所知测试已经对其进行了测试。这是一个更大的项目的一部分,因此我整理了几个(相对)小文件来说明问题。

其报告发现的行为:

  • 第10行是resolve({setTimeoutnew Promise回调内的fakePrefApiCall。 -此行应包括在内,因为“生成首选项字符串”测试会检查返回的承诺是否可以解决。
  • 第48行位于u.Preferences = pref.data;之内的findUserByName内-应该覆盖此行,因为“ find Abby”检查所解析的值是否具有正确的Preferences属性
  • 第50行是return u;中的findUserByName -与上面相同

我在这里做错什么了吗?

我发现使用/* istanbul ignore next */使Jest忽略该行。尽管我尝试过,但我并不完全热衷于简单地忽略事物。当我忽略了3条报告的行时,即使通过“ finds Abby”测试对其进行了测试,它也报告了38条未被发现(if (0 !== result.Path.indexOf(this.rootPath)) continue;)(在迭代1,4,5上为false,在迭代2,3上为true)


我得到的输出是:

$ jest --verbose --detectOpenHandles tests/jest-oddity.test.js
 PASS  tests/jest-oddity.test.js
  Testing line coverage
    √ fake API call resolves (20ms)
    √ generates preference strings (4ms)
    √ finds Abby (5ms)
    √ handles ambiguos users (4ms)
    √ handles missing users (4ms)

--------------------------|----------|----------|----------|----------|-------------------|
File                      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------------------|----------|----------|----------|----------|-------------------|
 *** IRRELEVANT LINES DELETED ***
  jest-oddity.js          |    81.82 |     87.5 |    83.33 |    83.33 |          10,48,50 |
--------------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       5 passed, 5 total
Snapshots:   0 total
Time:        3.857s
Ran all test suites matching /tests\\jest-oddity.test.js/i.
Done in 26.07s.

代码文件:

// jest-oddity.js
class SampleClass {
  constructor () {
    this.rootPath = '/users/corporate';
  }

  async fakePrefApiCall(uid) {
    return new Promise((resolve, reject) => {
      setTimeout((uid) => {
        resolve({
          data: `pref-string-${uid}`
        });
      }, 1000);
    });
  }

  async getPreferences(uid) {
    /*return Promise.resolve({
      data: `pref-string-${uid}`
    });*/

    return this.fakePrefApiCall(uid);
  }

  async findUserByName(user) {
    let d = [
      {Id: 1, Username: 'Abby', Path: '/users/corporate/asmith'},
      {Id: 2, Username: 'Bob', Path: '/users/external/bwilliams'},
      {Id: 3, Username: 'Carly', Path: '/users/sales/cpoe'},
      {Id: 4, Username: 'Dean', Path: '/users/corporate/dmiller'},
      {Id: 5, Username: 'Dean', Path: '/users/corporate/dsmith'}
    ];

    let candidates = [];
    for (let result of d) {
      if (result.Username != user) continue;
      if (0 !== result.Path.indexOf(this.rootPath)) continue;

      candidates.push(result);
    }

    if (!candidates.length) { return null; }
    else if (candidates.length > 1) { return Promise.reject(`Multiple (${candidates.length}) results found for ${user}`); }

    let u = candidates[0];
    let pref = await this.getPreferences(u.Id);

    u.Preferences = pref.data;

    return u;
  }
}

module.exports = SampleClass;

测试文件:

// jest-oddity.test.js
const SampleClass = require("./jest-oddity");

describe("Testing line coverage", () => {
  beforeAll(() => {
    testObj = new SampleClass();
  });

  it("fake API call resolves", () => {
    expect(testObj.fakePrefApiCall(22)).resolves.toMatchObject({
      data: 'pref-string-22'
    });
  });

  it("generates preference strings", () => {
    expect(testObj.getPreferences(57)).resolves.toEqual({data: 'pref-string-57'});
  });

  it("finds Abby", () => {
    let userPromise = testObj.findUserByName("Abby");
    expect(userPromise).resolves.toMatchObject({
      Username: 'Abby',
      Preferences: 'pref-string-1'
    });
  });

  it("handles ambiguos users", () => {
    expect(testObj.findUserByName("Dean")).rejects.toMatch('Multiple');
  });

  it("handles missing users", () => {
    expect(testObj.findUserByName("nonexistent")).resolves.toBe(null);
  })
});

0 个答案:

没有答案