JavaScript:Jest无法识别静态函数

时间:2019-08-08 23:20:12

标签: javascript jestjs

我正在关注一个使用玩笑来测试JavaScript的教程。讲师在名为genesis()的类上创建了名为Block的静态函数,该函数对他有效,但是当我尝试这样做时,我得到了TypeError: block.genesis is not a function。如果我删除了static关键字,它将识别该功能并且测试通过。

这是课程:

const { GENESIS_DATA } = require('./config');

class Block {
    constructor({ timestamp, lastHash, hash, data }) {
        this.timestamp = timestamp;
        this.lastHash = lastHash;
        this.hash = hash;
        this.data = data;
    }

    static genesis() {
        return new Block(GENESIS_DATA);
    }
}

module.exports = Block;

测试:

const Block = require('./block');
const { GENESIS_DATA } = require('./config');

describe('Block', () => {
    const timestamp = 'a-date';
    const lastHash = 'a-hash';
    const hash = 'another-hash';
    const data = ['blockchain', 'data'];
    const block = new Block({ timestamp, lastHash, hash, data });

    describe('genesis()', () => {
        const genesisBlock = block.genesis();

        it('returns a block instance', () => {
            expect(genesisBlock instanceof Block).toBe(true);
        });

        it('returns the genesis data', () => {
            expect(genesisBlock).toEqual(GENESIS_DATA);
        });
    });
});

1 个答案:

答案 0 :(得分:1)

genesis方法是类的一部分,而不是实例的一部分。您要呼叫Block.genesis()而不是block.genesis()