【问题标题】:Jest: Can only re-mock implementation when running a single test开玩笑:只能在运行单个测试时重新模拟实现
【发布时间】:2018-05-18 20:23:57
【问题描述】:

我有以下简化的示例,其中我手动模拟了一个依赖项并让它返回一个已解决的 Promise。然后,在我的一项测试中,我尝试将其返回类型更改为 Promise 拒绝。

如果我同时运行所有 3 个测试,它们会失败,因为测试中的拒绝调用实际上已解决。但是,如果我将规范中的第 17 行修改为 it.only('should reject if the client fails to load',则单个测试通过。

我做错了什么?

service.js:

import client from './client';

const service = (() => {
  let instance;

  const makeCall = () => {
    return true;
  };

  const init = async () => {
    const _client = await client();

    return Promise.resolve({
      makeCall,
    });
  };

  const getInstance = async () => {
    if (!instance) {
      instance = await init();
    }

    return Promise.resolve(instance);
  };

  return {
    getInstance,
  };
})();

export default service;

client.js:

const client = () => Promise.resolve('Real');

export default client;

__test__/service.spec.js:

import client from '../client';
import service from '../service';

jest.mock('../client');

describe('Service', () => {
  it('should return a singleton', () => {
    expect(service.getInstance()).toEqual(service.getInstance());
  });

  it('should resolve if the client successfully loads', async () => {
    expect.assertions(1);

    await expect(service.getInstance()).resolves.toHaveProperty('makeCall');
  });

  it('should reject if the client fails to load', async () => {
    const errorMessage = 'Client could not be initialised.';

    expect.assertions(1);
    client.mockReturnValueOnce(Promise.reject(new Error(errorMessage)));

    await expect(service.getInstance()).rejects.toHaveProperty(
      'message',
      errorMessage
    );
  });
});

__mocks__/client.js:

const client = jest.fn();
client.mockImplementation(() => {
  return Promise.resolve('Mock file');
});

export default client;

【问题讨论】:

    标签: javascript jestjs


    【解决方案1】:

    这是由于试图模拟单例的依赖关系造成的。

    在运行所有三个测试时,将使用原始模拟实现(解析),然后不会被拒绝的第二个模拟实现替换。

    还值得注意的是,由于创建了被拒绝的 Promise 但因此未处理,这会导致未处理的 Promise 拒绝和测试套件崩溃。

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 2018-11-27
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 2019-01-07
      • 1970-01-01
      • 2021-11-04
      相关资源
      最近更新 更多