Jest不承认对间谍的召唤

时间:2017-03-08 16:25:50

标签: javascript unit-testing jestjs

我想测试一个在promise中调用函数的方法。

article-api.js (简化)

articleMiddleware(next) {
    return fetch(articleApiListUrl, { headers, method, body })
        .then(() => next({ some: 'data'}));

}

这是article-api.js的简化版本,完整代码可以在这里看到: https://gist.github.com/LukasBombach/7bd9cce28d3a3b905fb8a408b37de3a9

我想知道next是否已使用{ some: 'data'}进行调用。我使用fetch-mock来模拟我的获取请求

article-api.spec.js (简化)

describe('article api middleware', () => {

    it('creates ARTICLE_SUCCESS when fetching an article has been done', () => {
        fetchMock.post('*', { some: 'data' });
        return articleMiddleware(next)
            .then(expect(next).toBeCalledWith({ some: 'data' }))
            .then(() => fetchMock.restore());

    });

});

这是article-api.spec.js的简化版本,完整代码可以在这里看到: https://gist.github.com/LukasBombach/178f591f516fe13c24fb0a4f02c4676c

我得到的是

  

最后一次调用的预期模拟函数:        [{some:' data' }]      但它没有被召集。

如果你查看两个要点中的完整代码,你会发现我的代码有点不同,那里的错误信息是

expect(received).toBe(expected)

Expected value to be (using ===):
  2
Received:
  1

这是因为第一个要点next(action)(同步)中第17行的next,但承诺中的next永远不会被调用。

1 个答案:

答案 0 :(得分:0)

这是仅使用"jest": "^24.8.0"的解决方案,无需使用fetch-mock,您可以自己手动模拟它。

article-api.js

const fetch = require('node-fetch');

function articleMiddleware(next) {
  const articleApiListUrl = 'https://github.com/mrdulin';
  const headers = {};
  const method = 'get';
  const body = {};

  return fetch(articleApiListUrl, { headers, method, body }).then(() => next({ some: 'data' }));
}

exports.articleMiddleware = articleMiddleware;

article-api.spec.js

jest.mock('node-fetch');

const fetch = require('node-fetch');
const { articleMiddleware } = require('./article-api');

describe('articleMiddleware', () => {
  it('t1', async () => {
    fetch.mockResolvedValueOnce({});
    const next = jest.fn();
    await articleMiddleware(next);
    expect(fetch).toBeCalledWith('https://github.com/mrdulin', { headers: {}, method: 'get', body: {} });
    expect(next).toBeCalledWith({ some: 'data' });
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/42676657/article-api.spec.js
  articleMiddleware
    ✓ t1 (9ms)

----------------|----------|----------|----------|----------|-------------------|
File            |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files       |      100 |      100 |      100 |      100 |                   |
 article-api.js |      100 |      100 |      100 |      100 |                   |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.131s

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/42676657