简体   繁体   中英

Can I monkey-patch dependencies when writing TypeScript unit tests

Our Web application has a very rich Javascript front-end, with a large number of custom widgets, wizards etc. We're looking at migrating some of it (perhaps eventually all) to TypeScript primarily for the benefits of easier refactoring/fewer bugs.

We've got JavaScript unit tests for widgets/client-side business logic - which we run through Karma. Currently our assertions all use the YUI test framework but we're not especially attached to that.

Since we're moving the code-base to TypeScript, it seems reasonable to consider writing some of the fixtures in TypeScript too (for the same benefits). Also note that the JavaScript output from our TypeScript code isn't quite as friendly as our hand-tooled JavaScript code, so that's another reason (to want to write the tests against the TypeScript).

Currently, some of our unit tests will "monkey-patch" a dependency to interrogate the code under test. For example, we might replace the browser's XmlHttpRequest object with a mock object so that we can reason about how our code interacts with the real XmlHttpRequest object.

We currently do that by just replacing the dependency for the duration of the test eg window.XmlHttpRequest = MyMockObject;

Does anyone have any thoughts on this practice, and in particular, thoughts on how achieving it in TypeScript differs from JavaScript?

Note that I'm not a fan of modifying our code for the sole purpose of making it easier to unit test (eg requiring the dependency is always injected rather than assumed to exist).

The sinon library (which has bindings for TypeScript) does this already, with special support for faking XMLHttpRequest (and timers). Using that where possible seems like the best option.

There's lots of ways to get around the type checking in TypeScript eg

  • Assigning a value of type any (always permitted)
  • Writing a JavaScript function to do your dirty work for you (and then writing a TypeScript definition for that function). That's basically what happens when using the sinon FakeXMLHttpRequest functionality from TypeScript
  • eval("foo = valueOfWrongType;");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM