使用Sinon进行Stub、Chai测试时出现firstName未定义报错求助
问题根源
- 触发报错的直接原因:测试代码中声明
expected对象时,直接使用了firstName、lastName、emailAddress三个未定义的变量,JS会将这些内容识别为要读取变量值,而你从未声明过这三个变量,因此直接抛出未定义错误。 - 预期值类型不匹配:业务代码最终返回的是逗号拼接的CSV格式字符串,你写的
expected是一个对象,就算解决变量报错,测试也不可能通过。 - stub未生效:你定义的
allApproverUserItemsForTeamstub没有传入createTeamApproversCsv,调用目标函数时只传了teamId,函数会使用默认的defaultAllApproverUserItemsForTeam实现,你写的stub完全没有起到作用。
修正后的测试代码
describe('create_team_approvers_csv_test', () => { describe('given a teamId for a team that has a list of approvers', () => { const teamId = randoms.randomId(); const allApproverUserItemsForTeam = sinon.stub(); const approversForTeam = [ { id: 'fwwfw', emailAddress: 'joe@bloggs.com', firstName: 'Joe', lastName: 'Bloggs', title: 'Mr', isTeamProfile: false, version: 1, }, { id: 'wgerher6446', emailAddress: 'jane@doe.com', firstName: 'Jane', lastName: 'Doe', title: 'Mrs', isTeamProfile: false, version: 3, }, ]; allApproverUserItemsForTeam.withArgs({ teamId }).returns(approversForTeam); it('should create a list of approvers in a required CSV format', () => { // 构造和业务输出格式一致的预期CSV字符串 const expected = 'Joe, Bloggs, joe@bloggs.com,Jane, Doe, jane@doe.com'; // 把stub传入目标函数替换默认实现 const result = createTeamApproversCsv({ teamId, allApproverUserItemsForTeam }); expect(result).to.be.equal(expected); }); }); });
内容的提问来源于stack exchange,提问作者Bjork
相关产品推荐
相关产品推荐

