как заменить импортированные модули заглушками

Я хотел бы заменить импортированные модули заглушками, чтобы сосредоточиться на модульном тестировании только основного модуля. Я пробовал использовать sinon.stub, но, похоже, он не делает то, что я ожидаю, так как я продолжаю получать сообщение об ошибке при запуске теста.

    { Error: Command failed: identify: unable to open image `test.exe': No such file or directory @ error/blob.c/OpenBlob/2724.
    identify: no decode delegate for this image format `EXE' @ error/constitute.c/ReadImage/504.

        at ChildProcess. (/node_modules/imagemagick/imagemagick.js:88:15)
        at ChildProcess.emit (events.js:159:13)
        at maybeClose (internal/child_process.js:943:16)
        at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5) timedOut: false, killed: false, code: 1, signal: null }

Вот мой основной модуль.


    // src/services/identifyService.js
    import imagemagick from 'imagemagick';

    class IdentifyService {
        async identify(filePath) {
            imagemagick.identify(['-format', '%w_%h', filePath], function(err, output) {
                if (err) reject(err);

                return resolve(output);
            });
        }
    }

И это мой тест.


    // test/identifyService.test.js
    import imagemagick from 'imagemagick';
    import IdentifyService from '../src/services/identifyService';

    describe('Verify image processing', () => {
        before(() => {
            const fileInfo = [{page: 1, width:100, height: 100, colorspace: 'RGB'}];
            sinon.stub(imagemagick, 'identify').returns(fileInfo);
        });

        it('returns metadata', (done) => {
            const metadata = IdentifyService.identify('test.exe');
            expect(metadata).to.have.lengthOf(0);
        });
    });

Я здесь что-то не так делаю? Любая помощь будет принята с благодарностью.


person ippomakunochi    schedule 13.07.2018    source источник


Ответы (1)


Во-первых, я обнаружил проблему с классом IdentifyService относительно использования promise.

class IdentifyService {
  identify(filePath) {
    return new Promise((resolve, reject) => { // create a new promise
      imagemagick.identify(['-format', '%w_%h', filePath], function (err, output) {
        if (err) reject(err);

        resolve(output); // no need to specify `return`
      });
    });
  }
}

Для самого теста он должен использовать yields вместо imagemagick.identify, потому что это функция с callback.

describe('Verify image processing', () => {
    before(() => {
        const fileInfo = [{page: 1, width:100, height: 100, colorspace: 'RGB'}];
        sinon.stub(imagemagick, 'identify').yields(null, fileInfo); // use yields
    });    

    it('returns metadata', async () => {
        const metadata = await IdentifyService.identify('test.exe');
        expect(metadata).to.have.lengthOf(0);
    });
});

Я предполагаю, что ваша среда поддерживает async await.

person deerawan    schedule 13.07.2018