【发布时间】: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