我正在将Karma与Mocha,Chai和Sinon一起使用this boilerplate在项目中测试代码。被测对象使用Speech Synthesis API。

我首先在window.speechSynthesis.getVoices方法中建立beforeEach

beforeEach(() => {
    global.window.speechSynthesis = {
        getVoices: () => (null),
    };
});


然后,我有两个测试用例,每个测试用例都想测试返回一组不同声音时会发生什么。为此,我使用Sinon stubs

第一个测试用例

it('supports speech and locale', () => {
    const getVoicesStub = sinon.stub(
        global.window.speechSynthesis,
        'getVoices');

    getVoicesStub.callsFake(() => (
        [{lang: 'en_US'}]
    ));


第二个测试用例

it('will choose best matching locale', () => {
    const getVoicesStub = sinon.stub(
        global.window.speechSynthesis,
        'getVoices');

    getVoicesStub.callsFake(() => (
        [{lang: 'es_MX'}, {lang: 'es_US'}]
    ));


问题是,当SUT在第二个测试用例中调用window.speechSynthesis.getVoices时,它正在从第一个存根中获取结果。好像第二个存根什么也不做...

如果我注释掉第一个测试用例,则第二个测试用例成功,但是如果我将它们都留在其中,则第二个测试用例将失败,因为返回了错误的声音集。

知道如何使第二个存根按预期工作吗?

最佳答案

测试之间不会破坏您的存根。测试后,您需要恢复默认功能,并且仅在before中创建一次存根

describe("Test suite", () => {

    let getVoicesStub;

    before(() => {
        // executes before suite starts
        global.window.speechSynthesis = {
            getVoices: () => (null),
        };

        getVoicesStub = sinon.stub(global.window.speechSynthesis, 'getVoices');
    });

    afterEach(() => {
        // executes after each test
        getVoicesStub.restore();
    });

    it('supports speech and locale', () => {
        getVoicesStub.callsFake(() => ([{lang: 'en_US'}]));
    });

    it('will choose best matching locale', () => {
        getVoicesStub.callsFake(() => ([{lang: 'es_MX'}, {lang: 'es_US'}]));
    });
});

关于javascript - 针对全局窗口的多个Sinon stub 未按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46332205/

10-11 05:57