本文整理汇总了TypeScript中Sinon.createSandbox函数的典型用法代码示例。如果您正苦于以下问题:TypeScript createSandbox函数的具体用法?TypeScript createSandbox怎么用?TypeScript createSandbox使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了createSandbox函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: describe
describe('File Manager', () => {
const configuration = new Configuration('manager.com', 'secret', 'appId');
const authenticator = new Authenticator(configuration);
const httpClient = new HTTPClient(authenticator);
const fileUploader = new FileUploader(configuration, httpClient);
const fileManager = new FileManager(configuration, httpClient, fileUploader);
const sandbox = sinon.createSandbox();
const apiServer = nock('https://manager.com/').defaultReplyHeaders({
'Content-Type': 'application/json',
});
afterEach(() => {
nock.cleanAll();
sandbox.verifyAndRestore();
});
it('listFiles - default', done => {
apiServer
.get('/_api/files/ls_dir')
.once()
.query(true)
.replyWithFile(200, repliesDir + 'list-files-response.json');
fileManager.listFiles('path').then(data => {
expect(data).to.deep.equal(
new ListFilesResponse({
nextPageToken: 'next',
files: [
{
id: 'd0e18fd468cd4e53bc2bbec3ca4a8676',
hash: 'd41d8cd98f00b204e9800998ecf8427e',
path: '/place-holder.txt',
mimeType: 'text/plain',
type: '-',
size: 0,
acl: 'public',
bucket: 'bucket-name',
dateCreated: '2017-02-20T14:23:42Z',
dateUpdated: '2017-02-20T14:23:42Z',
},
{
id: 'f65c0c70bec44b86bb543cc166800f03',
hash: null,
path: '/kb',
mimeType: DescriptorMimeType.Folder,
type: 'd',
size: 0,
acl: 'public',
bucket: null,
dateCreated: '2017-02-20T14:22:51Z',
dateUpdated: '2017-02-20T14:22:51Z',
},
].map(fileDescriptorData => new FileDescriptor(fileDescriptorData)),
}),
);
done();
});
});
it('listFiles - page', done => {
apiServer
.get('/_api/files/ls_dir')
.once()
.query({
path: 'path',
orderDirection: OrderDirection.ASC,
nextPageToken: 'c',
orderBy: 'date',
pageSize: 10,
type: FileType.FOLDER,
})
.replyWithFile(200, repliesDir + 'list-files-response.json');
fileManager
.listFiles('path', {
orderDirection: OrderDirection.ASC,
nextPageToken: 'c',
orderBy: 'date',
pageSize: 10,
type: FileType.FOLDER,
})
.then(() => {
done();
});
});
describe('createFolder', () => {
it('should return resolved promise with public folder(acl set with public by default)', done => {
apiServer
.post('/_api/files')
.once()
.query(true)
.replyWithFile(200, repliesDir + 'create-folder-success-response.json');
fileManager.createFolder({ path: 'bla' }).then(data => {
expect(data).to.deep.equal(
new FileDescriptor({
mimeType: DescriptorMimeType.Folder,
//.........这里部分代码省略.........
示例2: describe
describe("build()", () => {
const sandbox = Sinon.createSandbox();
before(() => {
sandbox.stub(HandlerBuilder.prototype as any, "invoke");
sandbox.stub(FilterBuilder.prototype, "build");
});
after(() => {
sandbox.restore();
});
afterEach(() => {
sandbox.resetHistory();
});
describe("when is a middleware", () => {
it("should have called invoke method with the correct parameters", inject([InjectorService], (injector: InjectorService) => {
// GIVEN
const handlerMetadata = new HandlerMetadata({
target: Test,
type: HandlerType.MIDDLEWARE,
method: "use"
});
// WHEN
const middleware: any = new HandlerBuilder(handlerMetadata).build(injector);
middleware({request: "request"}, {response: "response"}, "function");
// @ts-ignore
HandlerBuilder.prototype.invoke.should.have.been.calledWithExactly({request: "request"}, {response: "response"}, "function");
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_REQUEST});
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_RESPONSE});
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_NEXT_FN});
}));
});
describe("when is a middleware error", () => {
it("should have called invoke method with the correct parameters", inject([InjectorService], (injector: InjectorService) => {
// GIVEN
const handlerMetadata = new HandlerMetadata({
target: Test,
type: HandlerType.MIDDLEWARE,
method: "useErr"
});
const error = new Error();
// WHEN
const middleware: any = new HandlerBuilder(handlerMetadata).build(injector);
middleware(error, {request: "request"}, {response: "response"}, "function");
// @ts-ignore
HandlerBuilder.prototype.invoke.should.have.been.calledWithExactly({request: "request"}, {response: "response"}, "function", error);
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_REQUEST});
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_RESPONSE});
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_NEXT_FN});
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_ERR});
}));
});
describe("when is a controller injectable", () => {
it("should have called invoke method with the correct parameters", inject([InjectorService], (injector: InjectorService) => {
// GIVEN
Metadata.set(PARAM_METADATA, [{service: EXPRESS_NEXT_FN}, {service: EXPRESS_ERR}], Test, "get");
const handlerMetadata = new HandlerMetadata({
target: Test,
type: HandlerType.CONTROLLER,
method: "get"
});
const error = new Error();
// WHEN
const middleware: any = new HandlerBuilder(handlerMetadata).build(injector);
middleware(error, {request: "request"}, {response: "response"}, "function");
// @ts-ignore
HandlerBuilder.prototype.invoke.should.have.been.calledWithExactly({request: "request"}, {response: "response"}, "function", error);
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_NEXT_FN});
FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_ERR});
Metadata.set(PARAM_METADATA, undefined, Test, "get");
}));
});
});
示例3: beforeEach
beforeEach(() => {
sandbox = sinon.createSandbox();
});
示例4: describe
describe("AsyncSettings", function() {
const sinon = sinonStatic.createSandbox();
let browserApi: typeof SinonChrome;
let stubbedStorage: typeof SinonChrome.storage;
let stubbedStorageArea: SinonChrome.storage.StubbedStorageArea;
let log: Log;
let asyncSettings: AsyncSettings;
function createAsyncSettings(
defaultSettings = {},
storageReadyPromise = Promise.resolve(),
) {
const storageAvailabilityController = new Module("", log);
storageReadyPromise.then(() => storageAvailabilityController.startup());
const storageApiWrapper = new StorageApiWrapper(
null, log, stubbedStorage, storageAvailabilityController as any,
);
storageApiWrapper.startup();
return new AsyncSettings(
log,
null,
storageApiWrapper,
defaultSettings,
);
}
before(function() {
browserApi = createBrowserApi();
log = new Log();
});
beforeEach(function() {
// MUST be in beforeEach (due to browserApi.flush() in afterEach):
stubbedStorage = browserApi.storage;
stubbedStorageArea = stubbedStorage.local;
});
afterEach(function() {
browserApi.flush();
sinon.reset();
});
describe(".get()", function() {
it("should throw for a pref without a default", async function() {
// setup
stubbedStorageArea.get.resolves({});
asyncSettings = createAsyncSettings();
asyncSettings.startup();
await asyncSettings.whenReady;
// exercise + verify
assert.throws(() => asyncSettings.get("foo"));
});
it("should return the default if no value is set", async function() {
// setup
stubbedStorageArea.get.resolves({
foo: "bar",
});
asyncSettings = createAsyncSettings({
foo: "bar",
});
asyncSettings.startup();
await asyncSettings.whenReady;
// exercise
const result = await asyncSettings.get("foo");
// verify
sinon.assert.callCount(stubbedStorageArea.get, 1);
sinon.assert.calledWithMatch(stubbedStorageArea.get, {foo: "bar"});
assert.deepEqual(result, {foo: "bar"});
});
it("should return the stored value for a pref with both a default and a value", async function() {
// setup
stubbedStorageArea.get.resolves({
foo: "BAZ",
});
asyncSettings = createAsyncSettings({
foo: "baz",
});
asyncSettings.startup();
await asyncSettings.whenReady;
// exercise
const result = await asyncSettings.get("foo");
// verify
sinon.assert.callCount(stubbedStorageArea.get, 1);
sinon.assert.calledWithMatch(stubbedStorageArea.get, {foo: "baz"});
assert.deepEqual(result, {foo: "BAZ"});
});
});
describe(".onChanged", function() {
it("should ignore prefs without a default value", async function() {
// setup
asyncSettings = createAsyncSettings();
//.........这里部分代码省略.........
示例5: describe
describe('archive manager', () => {
const configuration = new Configuration('manager.com', 'secret', 'appId');
const authenticator = new Authenticator(configuration);
const httpClient = new HTTPClient(authenticator);
const archiveManager = new ArchiveManager(configuration, httpClient);
const sandbox = sinon.createSandbox();
const apiServer = nock('https://manager.com/').defaultReplyHeaders({
'Content-Type': 'application/json',
});
afterEach(() => {
nock.cleanAll();
sandbox.verifyAndRestore();
});
it('create archive', done => {
apiServer
.post('/_api/archive/create')
.once()
.query(true)
.replyWithFile(200, repliesDir + 'create-archive-pending-response.json');
const createArchiveRequest = new CreateArchiveRequest({
destination: {
directory: '/fish',
acl: ACL.PUBLIC,
},
sources: [
{
fileId: 'archive-file',
},
],
archiveType: 'zip',
});
archiveManager
.createArchive(createArchiveRequest)
.then((job: Job<CreateArchiveSpecification>) => {
expect(job.id).to.equal(
'6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
);
done();
});
});
it('should create archive observable', done => {
apiServer
.post('/_api/archive/create')
.once()
.query(true)
.replyWithFile(
200,
path.join(repliesDir, 'create-archive-pending-response.json'),
);
apiServer
.get(
'/_api/jobs/6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
)
.once()
.replyWithFile(
200,
path.join(repliesDir, 'create-archive-success-response.json'),
);
const progressSpy = sandbox.spy();
archiveManager
.createArchiveObservable({
destination: {
directory: '/fish',
acl: ACL.PUBLIC,
},
sources: [
{
fileId: 'archive-file',
},
],
archiveType: 'zip',
})
.subscribe(progressSpy, done, () => {
expect(progressSpy).to.have.been.calledTwice;
expect(progressSpy.firstCall.args[0].id).to.equal(
'6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
);
expect(progressSpy.firstCall.args[0].status).to.equal('pending');
expect(progressSpy.secondCall.args[0].id).to.equal(
'6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
);
expect(progressSpy.secondCall.args[0].status).to.equal('success');
done();
});
});
it('should create archive observable error', done => {
apiServer
.post('/_api/archive/create')
.once()
.query(true)
.replyWithFile(
//.........这里部分代码省略.........
示例6: beforeEach
beforeEach(function () {
sandbox = sinon.createSandbox();
});
示例7: describe
describe('Settings', () => {
const sandbox = Sinon.createSandbox();
describe('isAudioNotificationSupported', () => {
context('on macOS', () => {
beforeEach(() => {
sandbox.stub(process, 'platform').value('darwin');
});
afterEach(() => {
sandbox.restore();
});
it('should return true', () => {
assert.isTrue(Settings.isAudioNotificationSupported());
});
});
context('on Windows', () => {
context('version 7', () => {
beforeEach(() => {
sandbox.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('7.0.0');
});
afterEach(() => {
sandbox.restore();
});
it('should return false', () => {
assert.isFalse(Settings.isAudioNotificationSupported());
});
});
context('version 8+', () => {
beforeEach(() => {
sandbox.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('8.0.0');
});
afterEach(() => {
sandbox.restore();
});
it('should return true', () => {
assert.isTrue(Settings.isAudioNotificationSupported());
});
});
});
context('on Linux', () => {
beforeEach(() => {
sandbox.stub(process, 'platform').value('linux');
});
afterEach(() => {
sandbox.restore();
});
it('should return false', () => {
assert.isFalse(Settings.isAudioNotificationSupported());
});
});
});
describe('isNotificationGroupingSupported', () => {
context('on macOS', () => {
beforeEach(() => {
sandbox.stub(process, 'platform').value('darwin');
});
afterEach(() => {
sandbox.restore();
});
it('should return true', () => {
assert.isTrue(Settings.isNotificationGroupingSupported());
});
});
context('on Windows', () => {
context('version 7', () => {
beforeEach(() => {
sandbox.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('7.0.0');
});
afterEach(() => {
sandbox.restore();
});
it('should return false', () => {
assert.isFalse(Settings.isNotificationGroupingSupported());
});
});
context('version 8+', () => {
beforeEach(() => {
sandbox.stub(process, 'platform').value('win32');
sandbox.stub(os, 'release').returns('8.0.0');
//.........这里部分代码省略.........
示例8: beforeEach
beforeEach(() => {
sandbox = sinon.createSandbox();
container = createContainer();
loggerStub = container.get(Symbols.helpers.logger);
instance = new BlockProgressLogger(10, 2, 'My message', loggerStub);
});
示例9: beforeEach
beforeEach(() => {
sandbox = sinon.createSandbox();
container = createContainer();
clock = sandbox.useFakeTimers();
fakeConfig = { forging: { secret: ['secret1', 'secret2'] } };
jobsQueueStub = container.get(Symbols.helpers.jobsQueue);
loggerStub = container.get(Symbols.helpers.logger);
edStub = container.get(Symbols.helpers.ed);
slotsStub = container.get(Symbols.helpers.slots);
appStateStub = container.get(Symbols.logic.appState);
broadcasterLogicStub = container.get(Symbols.logic.broadcaster);
accountsModuleStub = container.get(Symbols.modules.accounts);
blocksModuleStub = container.get(Symbols.modules.blocks);
delegatesModuleStub = container.get(Symbols.modules.delegates);
transactionsModuleStub = container.get(Symbols.modules.transactions);
blocksProcessModuleStub = container.get(Symbols.modules.blocksSubModules.process);
sequenceStub = {
addAndPromise: sandbox.spy((w) => {
return Promise.resolve(
w()
);
}),
};
instance = new ForgeModule();
instance = instance as any;
instance.enabledKeys = {};
instance.config = fakeConfig;
instance.constants = constants;
instance.jobsQueue = jobsQueueStub;
instance.logger = loggerStub;
instance.ed = edStub;
instance.defaultSequence = sequenceStub;
instance.slots = slotsStub;
instance.appState = appStateStub;
instance.broadcasterLogic = broadcasterLogicStub;
instance.accountsModule = accountsModuleStub;
instance.blocksModule = blocksModuleStub;
instance.delegatesModule = delegatesModuleStub;
instance.transactionsModule = transactionsModuleStub;
instance.blocksProcessModule = blocksProcessModuleStub;
sha256Spy = sandbox.spy(supersha, 'sha256');
blocksModuleStub.lastBlock = BlocksModel.classFromPOJO({
blockSignature : Buffer.from('blockSignature'),
generatorPublicKey : Buffer.from('pubKey'),
height : 12422,
id : 'blockID',
numberOfTransactions: 0,
payloadHash : Buffer.from('payload'),
payloadLength : 0,
previousBlock : 'previous',
reward : 15,
timestamp : Date.now(),
totalAmount : 0,
totalFee : 0,
version : 1,
});
loadKeypairs = () => {
instance.enabledKeys = {
aaaa: true,
bbbb: true,
cccc: true,
};
instance.keypairs = {
aaaa: { publicKey: Buffer.from('aaaa', 'hex') },
bbbb: { publicKey: Buffer.from('bbbb', 'hex') },
cccc: { publicKey: Buffer.from('cccc', 'hex') },
};
};
});
示例10: beforeEach
beforeEach(() => {
sandbox = sinon.createSandbox();
container = createContainer();
instance = new TransactionPool();
fakeBus = {message: sandbox.stub().resolves()};
fakeAppState = {get: sandbox.stub()};
jqStub = container.get(Symbols.helpers.jobsQueue);
loggerStub = container.get(Symbols.helpers.logger);
transactionLogicStub = container.get(Symbols.logic.transaction);
accountsModuleStub = container.get(Symbols.modules.accounts);
balanceSequenceStub = container.getTagged(Symbols.helpers.sequence,
Symbols.helpers.sequence, Symbols.tags.helpers.balancesSequence);
// dependencies
(instance as any).bus = fakeBus;
(instance as any).jobsQueue = jqStub;
(instance as any).logger = loggerStub;
(instance as any).appState = fakeAppState;
(instance as any).balancesSequence = balanceSequenceStub;
(instance as any).transactionLogic = transactionLogicStub;
(instance as any).accountsModule = accountsModuleStub;
(instance as any).config = {
broadcasts: {
broadcastInterval: 1500,
releaseLimit: 100,
},
transactions: {
maxTxsPerQueue: 50,
},
};
instance.afterConstruction();
spiedQueues = {
bundled: {},
multisignature: {},
queued: {},
unconfirmed: {},
};
// we preserve behavior of the inner queues but we spy on all methods.
['unconfirmed', 'bundled', 'queued', 'multisignature'].forEach((queueName) => {
if (typeof spiedQueues[queueName] === 'undefined') {
spiedQueues[queueName] = {};
}
['has', 'remove', 'add', 'get', 'reindex', 'list', 'listWithPayload'].forEach((method: string) => {
spiedQueues[queueName][method] = sandbox.spy(instance[queueName], method);
});
});
tx = {
amount : 108910891000000,
asset : {},
fee : 10,
id : '8139741256612355994',
recipientId : '15256762582730568272R',
senderId : '1233456789012345R',
senderPublicKey: Buffer.from('6588716f9c941530c74eabdf0b27b1a2bac0a1525e9605a37e6c0b3817e58fe3', 'hex'),
signature : Buffer.from('f8fbf9b8433bf1bbea971dc8b14c6772d33c7dd285d84c5e6c984b10c4141e9f' +
'a56ace902b910e05e98b55898d982b3d5b9bf8bd897083a7d1ca1d5028703e03', 'hex'),
timestamp : 0,
type : TransactionType.SEND,
};
// Clone the tx to separate objects with different IDs
tx2 = Object.assign({}, tx);
tx2.id = 'tx2';
tx3 = Object.assign({}, tx);
tx3.id = 'tx3';
sandbox.resetHistory();
});