模拟 ES 模块是一个常见的用例。
例如,我有一个导入 getEventByEventId 的模块
import getEventByEventId from '../queries/getEventByEventId';
export default async (
{
connection,
session
}: ResolverContextType
) => {
if (!session || !session.userId) {
throw new Error('User must be authenticated.');
}
const event = await getEventByEventId(connection, eventId);
// ..
}
在我的测试中,我想模拟 getEventByEventId,例如
import test from 'ava';
import sinon from 'sinon';
import moment from 'moment';
import createReservation from '../../../src/mutators/createReservation';
test('throws an error if the event is in the past', async (t) => {
const parameters: any = {};
const context: any = {
session: {
userId: 1
}
};
const stub = sinon.stub().returns({
date: moment().format('YYYY-MM-DD'),
time: moment(new Date().getTime() - 1000 * 60).format('HH:mm')
});
// How to use the stub to mock `getEventByEventId`?
await t.throws(createReservation(context), 'Cannot create a reservation for a past event.');
});
Sinon.JS 不关心模块系统。 我正在关闭这个。
由于不断收到许多请求,并且该项目的管理员也以编写测试为生,因此我们发布了How To Use Link Seams With CommonJS 。
请帮助我们保持问题列表的可管理性,并在Sinon.JS 用户邮件列表或StackOverflow上提出使用问题。 两者都是很好的资源,更广泛的用户可以提供帮助。
@sebakerckhof结帐这个https://github.com/sinonjs/sinon/issues/562#issuecomment -399090111