我能够轻松地使用玩笑来模拟模块,例如:
import * as PubNub from 'pubnub';
jest.mock('pubnub', () =>
jest.fn().mockImplementation(() => {
mockPubnubInstance = {
addListener(options) {
mockPubnubListener(options);
},
publish() {
return Promise.resolve({});
},
subscribe: jest.fn(),
history(params, callback) {
return mockHistory(params, callback);
},
};
return mockPubnubInstance;
}),
);
我如何在赛普拉斯中做到这一点?
cy.stub('pubnub', 'publish').returns(Promise.resolve({}))
我尝试查看Cypress存根,但似乎不起作用。
答案 0 :(得分:0)
赛普拉斯内部使用(D*) (void*) (B*) d
(B*) (void*) d
作为其存根和间谍库。这是单元测试解决方案:
sinon
:
index.ts
import PubNub from 'pubnub';
export const pubnub = new PubNub({
publishKey: 'demo',
subscribeKey: 'demo'
});
export function publish() {
function publishSampleMessage() {
console.log("Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.");
var publishConfig = {
channel: 'hello_world',
message: {
title: 'greeting',
description: 'hello world!'
}
};
pubnub.publish(publishConfig, function(status, response) {
console.log(status, response);
});
}
pubnub.addListener({
status: function(statusEvent) {
if (statusEvent.category === 'PNConnectedCategory') {
publishSampleMessage();
}
},
message: function(msg) {
console.log(msg.message.title);
console.log(msg.message.description);
},
presence: function(presenceEvent) {
// handle presence
}
});
console.log('Subscribing..');
pubnub.subscribe({
channels: ['hello_world']
});
}
:
index.spec.ts
单元测试结果:
/// <reference types="Cypress" />
import { publish, pubnub } from './';
describe('59170422', () => {
it('should pass', () => {
const logSpy = cy.spy(console, 'log');
const addListenerStub = cy.stub(pubnub, 'addListener');
const publishStub = cy.stub(pubnub, 'publish').resolves({});
const subscribeStub = cy.stub(pubnub, 'subscribe');
publish();
addListenerStub.yieldTo('status', { category: 'PNConnectedCategory' });
expect(addListenerStub).to.have.been.calledOnce;
expect(publishStub).to.have.been.calledOnce;
expect(subscribeStub).to.have.been.calledOnce;
publishStub.yield(200, 'haha');
expect(logSpy).to.have.been.calledWith(200, 'haha');
addListenerStub.yieldTo('message', { message: { title: 'I am title', description: 'I am description' } });
expect(logSpy).to.have.been.calledWith('I am title');
expect(logSpy).to.have.been.calledWith('I am description');
});
});
源代码:https://github.com/mrdulin/cypress-codebase/tree/master/cypress/integration/stackoverflow/59170422