Mock函数后检查属性值触发AssertionError问题排查(Mocha/Sinon)
Let's walk through what's causing your test failure and fix it step by step:
1. First, a critical typo in your file.js
You wrote module.export instead of module.exports (missing the final s). This breaks the export of your param variable and test function, so your test can't properly access or interact with them. Fix that first:
// file.js const fs1 = require('fs'); let param; // Fixed: module.exports instead of module.export module.exports = { test, param } function test (outputParam) { param = fs1.readFileSync(outputParam); }
2. You never called the test function in your test!
Your test sets up a stub for readFileSync and defines a mock expectation for test, but it never actually runs filejs.test(someArg). That means param is never assigned a value—it stays as the initial undefined, which is why your assertion fails.
3. Clean up your sinon mock usage
When using sinon.mock, you need to verify that the expectation was met after calling the function. Also, since you're just returning a fixed value from readFileSync, you can use the simpler .returns() method instead of callsFake.
Here's the fixed test code:
// test.spec.js let expect = require('chai').expect; let fs = require("fs"); let sinon = require("sinon"); let filejs = require('./file.js'); it('should set variable param to `this is my file content` when test is called', function() { let someArg = "file.xml"; // Stub fs.readFileSync to return our test content (simpler than callsFake) const readFileSyncStub = sinon.stub(fs,'readFileSync').returns("this is my file content"); // Create mock to verify test is called once with the correct argument const mock = sinon.mock(filejs); mock.expects('test').once().withArgs(someArg); // 👉 This is the missing step: actually execute the test function! filejs.test(someArg); // Verify that our mock expectation was satisfied mock.verify(); // Now check if param has the expected value expect(filejs.param).to.equal('this is my file content'); // Restore the stub to avoid messing up other tests (good practice) readFileSyncStub.restore(); })
Key fixes explained:
- Fixed the module export typo to properly expose
paramandtest - Added the critical call to
filejs.test(someArg)so the function runs and assigns a value toparam - Used
.once()to make the mock expectation explicit (we expect exactly one call totest) - Switched to
.returns()for the stub since we're just returning a static value - Added stub restoration to keep tests isolated from each other
内容的提问来源于stack exchange,提问作者karansys

